我无法使用Node.getNodeValue()Node.getFirstChild().getNodeValue()Node.getTextContent()获取文本值。

我的XML就像

<add job="351">
    <tag>foobar</tag>
    <tag>foobar2</tag>
</add>

而且我正在尝试获取标签值(非文本元素提取工作正常)。我的Java代码听起来像
Document doc = db.parse(new File(args[0]));
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;

for (int i=0; i < nl.getLength(); i++) {
    an = nl.item(i);

    if(an.getNodeType()==Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for(int i2=0; i2<nl2.getLength(); i2++) {
            an2 = nl2.item(i2);

            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");

            if(an2.hasChildNodes())
                System.out.println(an2.getFirstChild().getTextContent());

            if(an2.hasChildNodes())
                System.out.println(an2.getFirstChild().getNodeValue());

            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }
    }
}

打印出来
tag type (1):
tag1
tag1
tag1
null
#text type (3):
_blank line_
_blank line_
...

谢谢您的帮助。

最佳答案

我还将打印出an2.getNodeName()的结果,以用于调试。我的猜测是您的树爬网代码没有爬到您认为是的节点上。由于没有检查代码中的节点名称,这种怀疑得到了加强。

除此之外,Node的javadoc定义“getNodeValue()”以为Element类型的Node返回null。因此,您确实应该使用getTextContent()。我不确定为什么不给您想要的文字。

也许迭代标签节点的子节点,看看那里有什么类型?

尝试了这段代码,它对我有用:

String xml = "<add job=\"351\">\n" +
             "    <tag>foobar</tag>\n" +
             "    <tag>foobar2</tag>\n" +
             "</add>";
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayInputStream bis = new ByteArrayInputStream(xml.getBytes());
Document doc = db.parse(bis);
Node n = doc.getFirstChild();
NodeList nl = n.getChildNodes();
Node an,an2;

for (int i=0; i < nl.getLength(); i++) {
    an = nl.item(i);
    if(an.getNodeType()==Node.ELEMENT_NODE) {
        NodeList nl2 = an.getChildNodes();

        for(int i2=0; i2<nl2.getLength(); i2++) {
            an2 = nl2.item(i2);
            // DEBUG PRINTS
            System.out.println(an2.getNodeName() + ": type (" + an2.getNodeType() + "):");
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getTextContent());
            if(an2.hasChildNodes()) System.out.println(an2.getFirstChild().getNodeValue());
            System.out.println(an2.getTextContent());
            System.out.println(an2.getNodeValue());
        }
    }
}

输出为:
#text: type (3): foobar foobar
#text: type (3): foobar2 foobar2

10-07 19:22
查看更多