我的 xml 文件包含:
<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<ContactGroup1>
<person aa="sads">
<name>Aghil</name>
<emailid>aghilvarghese@gmail.com</emailid>
</person>
</ContactGroup1>
</Contacts>
我正在尝试通过以下 java 代码阅读此内容:
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = (Document) dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("ContactGroup1");
Node nNode = nList.item(0);//take first cgroup
NodeList nl = (nNode.getChildNodes());
System.out.println("nodes in ContactGroup1 : " + nl.getLength());
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
System.out.println("node type is " + node.getNodeType() + " " + node.getNodeName());
}
输出是:
根元素:联系人 ContactGroup1 中的节点:3 节点类型为 3 #text 节点类型为1人 节点类型为 3 #text
但是在 ContactGroup1 中只有一个节点(即人),不是吗?为什么这个错误的输出?我该怎么做才能让它正确?