获取XML节点的getNodeName()操作返回#text。

10
<person>
<firstname>
<lastname>
<salary>
</person>

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

text

firstname

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();
}

代码已经提供,请帮忙。 - coder
1个回答

6

setIgnoringElementContentWhitespace仅在使用setValidating(true)时才起作用,而且仅当您解析的XML文件引用了解析器可以使用的DTD以确定哪些仅包含空格的文本节点实际上是可忽略的时才起作用。如果您的文档没有DTD,则会出于安全考虑假定不能忽略任何文本节点,因此您必须编写自己的代码来在遍历子节点时忽略它们。


非常感谢您的回复。哪种方法更好?编写DTD还是编写忽略空格的方法? - coder
2
后期去除只包含空白字符的文本节点并不难(例如:http://www.java.net/node/667186#comment-684625),这样就避免了修改原始XML文件来添加DTD引用的必要。 - Ian Roberts
如果这个答案对您有帮助,请考虑通过点击左侧的绿色勾号“接受”它。 - Ian Roberts

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接