我无法获取文本值Node.getNodeValue()
,Node.getFirstChild().getNodeValue()
或者用Node.getTextContent()
.
我的XML就像
foobar foobar2
而我正在尝试获取标记值(非文本元素提取工作正常).我的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打印出来
tag type (1): tag1 tag1 tag1 null #text type (3): _blank line_ _blank line_ ...谢谢您的帮助.
1> jsight..:我也打印出
an2.getNodeName()
调试结果.我的猜测是你的树爬行代码没有爬到你认为它的节点.由于缺乏对代码中节点名称的检查,这种怀疑得到了加强.除此之外,Node的javadoc定义" getNodeValue()"为Element类型的节点返回null.因此,你真的应该使用getTextContent().我不确定为什么那不会给你你想要的文字.
也许迭代你的标记节点的子节点,看看有哪些类型?
试过这段代码,它对我有用:
String xml = "\n" + " "; 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; i2foobar \n" + "foobar2 \n" + "产出是:
#text: type (3): foobar foobar #text: type (3): foobar2 foobar2
2> toolkit..:如果您的XML非常深入,您可能需要考虑使用JRE附带的XPath,以便您可以更轻松地使用以下内容访问内容:
String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()", document.getDocumentElement());完整示例:
import static org.junit.Assert.assertEquals; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.junit.Before; import org.junit.Test; import org.w3c.dom.Document; import org.xml.sax.InputSource; public class XPathTest { private Document document; @Before public void setup() throws Exception { String xml = ""; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); document = db.parse(new InputSource(new StringReader(xml))); } @Test public void testXPath() throws Exception { XPathFactory xpf = XPathFactory.newInstance(); XPath xp = xpf.newXPath(); String text = xp.evaluate("//add[@job='351']/tag[position()=1]/text()", document.getDocumentElement()); assertEquals("foobar", text); } } foobar foobar2