我一直在尝试使用从其他帖子中找到的代码来解析 xml 字符串,但是当尝试获取节点元素时,我不断获取空值。有人可以看到错误或我缺少的东西吗?
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(post));
Document doc;
try {
doc = db.parse(is);
doc.getDocumentElement().normalize();
Element root = doc.getDocumentElement();
NodeList nodes = root.getElementsByTagName("entry");
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
根元素为空,节点列表也为空。 XML 帖子开头为:
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:activity="http://activitystrea.ms/spec/
1.0/" xmlns:service="http://activitystrea.ms/
service-provider" xmlns:thr="http://purl.org/syndication/thread/1.0"
xmlns:gnip="http://www.post.com/schemas/2010"
xmlns:geo="http://www.georss.org/georss" xmlns:poco="http://portablecontacts.net/spec/1.0">
<id>...
编辑:
NodeList nodes.. //The value of the local nodes is not used
[entry: null]
// it skips the following lines...
for(int i=0; i < nodes.getLength() - 1; i++){
System.out.println(nodes.item(i).toString());
}
最佳答案
替换 NodeList 节点 = root.getElementsByTagName("entry");
by NodeList 节点 = root.getChildNodes();
关于java - java中解析xml字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25493605/