【问题标题】:getNodeName() operation on an XML node returns #textXML 节点上的 getNodeName() 操作返回 #text
【发布时间】:2012-09-30 18:53:20
【问题描述】:
<person>
<firstname>
<lastname>
<salary>
</person>

这是我正在解析的 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();
}

【问题讨论】:

  • 已提供代码。请帮忙

标签: java xml dom xml-parsing


【解决方案1】:

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

【讨论】:

  • 非常感谢您的回复。哪种方法更可取?编写 DTD 还是编写忽略空格的方法?
  • 事后去掉只有空格的文本节点并不难(例如java.net/node/667186#comment-684625),这避免了修改原始 XML 文件以添加 DTD 引用的需要。
  • 这太棒了!非常感谢!
  • 如果答案对您有用,请考虑接受点击左侧的绿色勾号。
猜你喜欢
  • 2012-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-06
  • 1970-01-01
  • 2017-04-12
  • 1970-01-01
  • 2012-09-23
相关资源
最近更新 更多