我有一个 XML 如下:
<parent>
<child1>
</child1>
<child2>
</child2>
</parent>
<parent>
<child3>
</child3>
<child4>
</child4>
</parent>
能够使用以下代码读取第一个父级的子节点值:
// Get the staff element by tag name directly
Node PatientVariables = doc.getElementsByTagName("parent").item(0);
// loop the staff child node
NodeList patientlist = PatientVariables.getChildNodes();
for (int i = 0; i < patientlist.getLength(); i++) {
Node node = patientlist.item(i);
if ("child1".equals(node.getNodeName())) {
PatientLastNameValue=node.getTextContent();
//System.out.println("The XML value:"+node.getTextContent() );
}
但是我无法读取第二个父节点值(child3 和 child4)
最佳答案
XML 只允许有一个根节点。将您的“父”节点放在根节点下,如下所示:
<root>
<parent>
...
</parent>
<parent>
...
</parent>
</root>
然后对 root 的子节点进行交互。
关于java - java中读取XML的所有父节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32475102/