File fXmlFile = new File(path);//path is a String
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document XMLbook = dBuilder.parse(fXmlFile);
Node root = XMLbook.getFirstChild(); //(1)
Node book = XMLbook.getElementsByTagName("BOOK").item(0);//(2)
Node lastChapter=book.getLastChild();//(3)
Node lastSubChapter=lastChapter.getLastChild(); //(4)
...
}
问题是它在 lastSubChapter
处达到 null,所以我的程序结束得很糟糕:(而且我不知道我做错了什么......代码看起来没问题。
另外,我不明白 NULL 代表什么:节点值?
- [ROOT: NULL ] - 我在调试时看到的内容
- [ BOOK: NULL]-我在调试时看到的内容
- [ #text: ] - 我在调试时看到的内容 - 这意味着什么?
- 问题!!这里
lastSubChapter
得到 NULL :( 为什么?
我正在读取的 XML 文件是:
<?xml version="1.0"?>
<ROOT>
<TITLE>Portocalia ca zapada</TITLE>
<BOOK>
<Chapter name="1">
<Subchapter name="1.1">
<paragraph>Primul paragraf!</paragraph>
</Subchapter>
</Chapter>
<Chapter name="2">
<Subchapter name="2.1">
<paragraph>A fost o data ca niciodata</paragraph>
</Subchapter>
<Subchapter name="2.2">
<paragraph>In luna a13a ea s-a maritat.</paragraph>
</Subchapter>
<Subchapter name="2.3">
<paragraph>In continuare, bineinteles</paragraph>
<paragraph>asa cum se intampla in toate povestile</paragraph>
</Subchapter>
</Chapter>
</BOOK>
</ROOT>
我想获取最后一个节点Subchapter
,其名称为“2.3”。
还有其他更安全的方法可以获取它吗?
最佳答案
由于 XML 内容的缩进,BOOK
和 Chapter
的子元素也包含空格(即文本内容)。因此 getLastChild
正在检索空白文本而不是元素。
您可以简单地通过 Element#getElementsByTagName
访问元素并获取最后一个节点。
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document XMLbook = dBuilder.parse(fXmlFile);
Node root = XMLbook.getFirstChild(); //(1)
Node book = XMLbook.getElementsByTagName("BOOK").item(0);//(2)
NodeList chapterNodes = ((Element)book).getElementsByTagName("Chapter");
if(chapterNodes != null && chapterNodes.getLength() > 0) {
Node chapterNode = chapterNodes.item(chapterNodes.getLength() - 1);
NodeList subChapterNodes = ((Element)chapterNode).getElementsByTagName("Subchapter");
if(subChapterNodes != null && subChapterNodes.getLength() > 0) {
Node subChapterNode = subChapterNodes.item(subChapterNodes.getLength() - 1);
System.out.println(subChapterNode.getNodeName());
}
}
关于java - 尝试用 Java 获取 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26785018/