我正在创建一个应用程序,该应用程序应该使用SAX(javax.xml.parsers.SAXParser)来解析包含有关各个位置信息的XML文件,以便这些位置可以显示为点在地图上;不幸的是,我的解析器遇到了问题。看似随机的SAX输出错误
的XML文件是由超过1000个重复的组是这个样子的:
<Placemark id="00001">
<name>Place name</name>
<address>Place address</address>
<ExtendedData>
<Data name="postcode">
<value>Place postcode</value>
</Data>
</ExtendedData>
<Point>
<coordinates>-0.000000,51.000000</coordinates>
</Point>
</Placemark>
我的XML处理程序检查,看看当前元素的名称,然后添加元素的值的相关列表,即
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if(localName.equals("placemark")) list.setPlaceID(attributes.getValue("id"));
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if(localName.equals("name")) list.setName(currentValue);
else if(localName.equals("address")) list.setAddress(currentValue);
else if(localName.equals("value")) list.setPostCode(currentValue);
else if(localName.equals("coordinates")) System.out.println(currentValue);
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException{
currentValue = new String(ch, start, length);
}
这成功地处理案件99.9%,但由于某些原因,我想不出还有一些特殊的XML坐标产生解析时意外输出的元素,例如:
<coordinates>-0.328459,51.604121</coordinates>
产生4121
而非-0.328459,51.604121
<coordinates>-0.060226,51.602341</coordinates>
产生26,51.602341
而非-0.060226,51.602341
甚至更令人混淆,如果有问题的元件是分离的,然后它们可以毫无问题地解析。只有当一个非常大的数字被解析时,只有少数人会导致这个问题。
是否有任何明显的解释可以解释这些结果?
请参阅http://stackoverflow.com/questions/8461723/xml-node-text-is-causing-issues-when-it-has-funny-characters/8676370#8676370 – 2011-12-30 14:41:46
太棒了!这工作完美,我不再收到任何意想不到的输出。非常感谢您的帮助! – Wolvern 2011-12-30 14:57:47
乐意帮忙!使用StringBuilder.append而不是字符串连接。这在某些情况下可以提高性能,这是最佳做法。 – 2011-12-30 15:02:38