英文:
parsing Xml for Java
问题
以下是翻译好的部分:
存在这样的XML文档:
<?xml version="1.0" encoding="utf-8"?>
<root>
<a/>
<a/>
<a/>
<b>
<c/>
<d/>
<c/>
<d/>
<c/>
<d/>
</b>
</root>
以下代码用于获取 "a" 节点的NodeList:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlfile);
doc.getDocumentElement().normalize();
NodeList aNodes = doc.getElementsByTagName("a");
但是,在Java中如何检索 "c" 节点的NodeList呢?
我尝试获取 "b" 节点的子节点,但是没有结果,getLength() = 0。
NodeList bNodes = doc.getElementsByTagName("b");
NodeList cNodes = bNodes.item(0).getChildNodes();
英文:
There exists XML document like this:
<?xml version="1.0" encoding="utf-8"?>
<root>
<a/>
<a/>
<a/>
<b>
<c/>
<d/>
<c/>
<d/>
<c/>
<d/>
</b>
</root>
Following code is using to get "a" NodeList:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlfile);
doc.getDocumentElement().normalize();
NodeList aNodes = doc.getElementsByTagName("a");
But how in Java I can retrieve NodeList of "c"?
I tried to get nodes of "b" nodes but it have not results, getlength() = 0.
NodeList bNodes = doc.getElementsByTagName("b");
NodeList cNodes = bNodes.item(0).getChildNodes();
答案1
得分: 1
你可以像这样使用 doc.getElementsByTagName("c")
来获取它们。
NodeList cNodes = doc.getElementsByTagName("c");
for (int i = 0; i < cNodes.getLength(); ++i)
System.out.println(cNodes.item(i));
输出:
[c: null]
[c: null]
[c: null]
我也可以检索到 "b" 的 NodeList。
NodeList bNodes = doc.getElementsByTagName("b");
NodeList bChildren = bNodes.item(0).getChildNodes();
for (int i = 0; i < bChildren.getLength(); ++i)
System.out.println(bChildren.item(i));
输出:
[#text:
]
[c: null]
[#text:
]
[d: null]
[#text:
]
[c: null]
[#text:
]
[d: null]
[#text:
]
[c: null]
[#text:
]
[d: null]
[#text:
]
英文:
You can get them by doc.getElementsByTagName("c")
like this.
NodeList cNodes = doc.getElementsByTagName("c");
for (int i = 0; i < cNodes.getLength(); ++i)
System.out.println(cNodes.item(i));
output:
[c: null]
[c: null]
[c: null]
I can also retrieve NodeList of "b".
NodeList bNodes = doc.getElementsByTagName("b");
NodeList bChildren = bNodes.item(0).getChildNodes();
for (int i = 0; i < bChildren.getLength(); ++i)
System.out.println(bChildren.item(i));
output:
[#text:
]
[c: null]
[#text:
]
[d: null]
[#text:
]
[c: null]
[#text:
]
[d: null]
[#text:
]
[c: null]
[#text:
]
[d: null]
[#text:
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论