我还将打印出结果
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



