XML节点上的getNodeName()操作返回#text

cod*_*der 9 java xml dom xml-parsing

<person>
<firstname>
<lastname>
<salary>
</person>
Run Code Online (Sandbox Code Playgroud)

这是我正在解析的XML.当我尝试打印人的子元素的节点名称时,我得到了

文本

名字

文本

姓

文本

薪水

如何消除正在生成的#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();
}
Run Code Online (Sandbox Code Playgroud)

Ian*_*rts 5

setIgnoringElementContentWhitespace仅在您使用时才有效setValidating(true),然后仅当您正在解析的XML文件引用DTD时,解析器才能使用该DTD来确定哪些只有空格的文本节点实际上是可忽略的.如果您的文档没有DTD,则它在安全方面会出错并假定不能忽略任何文本节点,因此您必须编写自己的代码以在遍历子节点时忽略它们.

  • 在事后删除仅空白文本节点并不难(例如http://www.java.net/node/667186#comment-684625),这样就无需修改原始XML文件来添加DTD参考. (2认同)