My xml file contains :
<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<ContactGroup1>
<person aa="sads">
<name>Aghil</name>
<emailid>aghilvarghese@gmail.com</emailid>
</person>
</ContactGroup1>
</Contacts>
I am trying to read this by following java code :
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());
}
The output is :
Root element :Contacts nodes in ContactGroup1 : 3 node type is 3 #text node type is 1 person node type is 3 #text
But in ContactGroup1 there is only one node (ie person), isn't it? Why this wrong output? What can I do to get it correct?
You can skip empty text nodes. Check this question: How to remove #text from my Node parsing in Java dom xml parsing So basically you should check it node is text and empty then skip it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.