java读取xml时输出错误 [英] Wrong output while reading xml by java
本文介绍了java读取xml时输出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的xml文件包含:
My xml file contains :
<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<ContactGroup1>
<person>
<name>Raj</name>
<emailid>rajdevp@gmail.com</emailid>
</person>
</ContactGroup1>
</Contacts>
我试图通过以下java代码来阅读:
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
< br $>
但是在ContactGroup1中只有一个节点(即人),不是吗?
为什么输出错误?我该怎么做才能使它正确?
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?
推荐答案
我将xml更改为:
I changed xml to :
<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
<ContactGroup1><person>
<name>Aghil</name>
<emailid>aghilvarghese@gmail.com</emailid>
</person></ContactGroup1>
</Contacts>
现在还可以。
And now its OK.
使用DTD验证,解析器会自动抑制元素之间的空白。
With DTD validationthe parser automatically suppress the whitespace between elements.
这篇关于java读取xml时输出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文