我的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());
}
输出结果为:
Root element :Contacts nodes in ContactGroup1 : 3 node type is 3 #text node type is 1 person node type is 3 #text
但在ContactGroup1中只有一个节点(即人),不是吗? 为什么输错了?我该怎么做才能使它正确?
答案 0 :(得分:0)
您可以跳过空文本节点。请检查此问题:How to remove #text from my Node parsing in Java dom xml parsing 所以基本上你应该检查节点是文本而空是然后跳过它。