<person>
<firstname>
<lastname>
<salary>
</person>
这是我正在解析的 XML。当我尝试打印 person 的子元素的节点名称时,
我明白了
text
名
text
lastname
text
salary
如何消除生成的#text?
更新 -
这是我的代码
try {
NodeList nl = null;
int l, i = 0;
File fXmlFile = new File("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
dbFactory.setValidating(false);
dbFactory.setIgnoringElementContentWhitespace(true);
dbFactory.setNamespaceAware(true);
dbFactory.setIgnoringComments(true);
dbFactory.setCoalescing(true);
InputStream in;
in = new FileInputStream(fXmlFile);
Document doc = dBuilder.parse(in);
doc.getDocumentElement().normalize();
Node n = doc.getDocumentElement();
System.out.println(dbFactory.isIgnoringElementContentWhitespace());
System.out.println(n);
if (n != null && n.hasChildNodes()) {
nl = n.getChildNodes();
for (i = 0; i < nl.getLength(); i++) {
System.out.println(nl.item(i).getNodeName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
setIgnoringElementContentWhitespace
仅当您使用时才有效setValidating(true)
,然后仅当您正在解析的 XML 文件引用 DTD 时,解析器才能使用该 DTD 来确定哪些纯空白文本节点实际上是可忽略的。如果您的文档没有 DTD,那么出于安全考虑,它会假定没有文本节点可以被忽略,因此您必须编写自己的代码来在遍历子节点时忽略它们。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)