我目前在SAXParserFactory中使用SAXParser,我遇到了字符串在'&‘符号处被截断的问题。例如:“国家创造了我们的世界&其中的一切”变成了“其中的一切”。
显然,我不希望这种情况发生。在xml输入中,字符被正确地转义为&。我该如何解决这个问题?
try{
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader r = sp.getXMLReader();
//This handles the xml and populates the entries array
XMLHandler handler = new XMLHandler();
// register event handlers
r.setContentHandler(handler);
String url = "http://foobar.xml";
r.parse(url);
return handler.getEntries();
}在我的DefaultHandler类中有这个
....
public void characters( char ch[], int start, int length ){
String value = new String( ch , start , length );
if(!value.trim().equals("")) {
if( currentElement.equalsIgnoreCase("TITLE") ) {
tempEntry.setTitle(value);
}
....发布于 2010-07-29 00:07:12
SAX API不能保证任何给定的文本节点都将被完整地交付。允许将其分解为对characters()方法的多个调用。您的应用程序必须尽可能地适应这一点,并自行重新组装这些片段。
顺便说一句,Nation Created Our World & everything in it不是有效的XML文本片段,它必须是Nation Created Our World & everything in it。在这种情况下,SAX解析器可能会将其分解为Nation Created Our World、&和everything in it,而您的应用程序只记住最后一个。
发布于 2013-08-10 03:09:34
谢谢斯卡夫曼
实现,
public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {
// clear tmpValue on start of element
tmpValue = "";
}
public void characters(char[] ac, int i, int j) throws SAXException {
tmpValue += new String(ac, i, j);
}https://stackoverflow.com/questions/3354811
复制相似问题