我正在使用SAX来解析我从网上提取的XML文件。我使用类似于以下代码扩展了DefaultHandler
public class ArrivalHandler extends DefaultHandler {
@Override
public void startElement(String namespaceUri, String localName, String qualifiedName, Attributes attributes) throws SAXException {
if (qualifiedName.equalsIgnoreCase("resultSet")) {
System.out.println("got a resultset");
} else if (qualifiedName.equalsIgnoreCase("location")) {
System.out.println("got a location");
} else if (qualifiedName.equalsIgnoreCase("arrival")) {
System.out.println("got an arrival");
} else {
System.out.println("There was an unknown XML element encountered: '" + qualifiedName + "'");
}
}
@Override
public void endElement(String namespaceUri, String localName, String qualifiedName) throws SAXException {
// we'll just ignore this for now
}
@Override
public void characters(char[] chars, int startIndex, int length) throws SAXException {
// ignore this too
}
}
我遇到的问题是我只是得到一系列空元素。日志显示:
There was an unknown XML element encountered: ''
There was an unknown XML element encountered: ''
There was an unknown XML element encountered: ''
etc
当我只是传递parser.parse
本地文件时,这很好用,但现在我将它从网上拉出来:
HttpClient httpClient = new DefaultHttpClient();
resp = httpClient.execute("http://example.com/whatever");
SAXParserFactory saxFactory = SAXParserFactory.newInstance();
ArrivalHandler handler = new ArrivalHandler();
SAXParser parser = saxFactory.newSAXParser();
parser.parse(resp.getEntity().getContent(), handler);
我得到了(显然)空的结果。
到目前为止我已经研究过了:
InputStream
从resp.getEntity().getContent()
转换为字符串并将其转储出来,看起来我正确地从服务器获取XML。W/ExpatReader(232): DTD handlers aren't supported.
”。 我正在做错的任何其他想法或如何调试它?
答案 0 :(得分:3)
来自docs for ContentHandler.startElement
:
时需要限定名称 namespace-prefixes属性是 是的,并且是可选的 namespace-prefixes属性为false (默认)。
那么,你是否将namespace-prefixes属性设置为true
?
你可以改为使用uri和localName吗?