首先,我有 xml 文件:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<bookshelf>
<book ISBN="c01" press="AD press">
<book>Oracle</book>
<Author>Smith</Author>
<price>32.00</price>
</book>
<book ISBN="b11" press="XY press">
<book>Android</book>
<Author>Smith</Author>
<price>35.00</price>
</book>
</bookshelf>
然后有java代码:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(currentPath + "/book.xml");
for (int i = 0; i < 2; ++i) {
System.out.println("begin");
Node n = document.getElementsByTagName("book").item(i);
Element e = (Element) n;
System.out.println(e.getAttribute("ISBN"));
System.out.println(e.getAttribute("press"));
System.out.println("end");
}
然后打印:
begin
b11
XY press
end
begin
end
这对我来说很奇怪:
(1) 为什么打印的第一个元素是“b11”而不是“c01”?这是第一个元素。
(2) 为什么只打印一个“book”元素,另一个为空?
非常感谢。
最佳答案
(1) Why the first element printed is "b11" but not "c01"? It's the first element.
对我来说没有。我得到了 c01
,然后是一个空白条目,考虑到输入,这是有意义的。
(2) Why only one "book" element is printed, the other is empty?
因为您在其他 book
元素中有 book
元素。 getElementsByTagName
返回所有四个。第二个是嵌套在第一个中的:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<bookshelf>
<book ISBN="c01" press="AD press"> #1 (index 0)
<book>Oracle</book> #2 (index 1)
<Author>Smith</Author>
<price>32.00</price>
</book>
<book ISBN="b11" press="XY press"> #3 (index 2)
<book>Android</book> #4 (index 3)
<Author>Smith</Author>
<price>35.00</price>
</book>
</bookshelf>
我对这个特定的 API 不太熟悉,但是如果我得到 bookshelf
然后循环它的子项并挑选出 book
的,我得到预期的输出:
import javax.xml.parsers.*;
import org.w3c.dom.*;
class Example {
public static final void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse("book.xml");
NodeList bookshelves = document.getElementsByTagName("bookshelf");
if (bookshelves.getLength() > 0) {
Element bookshelf = (Element)bookshelves.item(0);
NodeList children = bookshelf.getChildNodes();
for (int i = 0, l = children.getLength(); i < l; ++i) {
Node child = children.item(i);
if (child.getNodeName().equals("book")) {
Element book = (Element)child;
System.out.println(book.getAttribute("ISBN"));
System.out.println(book.getAttribute("press"));
}
}
}
}
}
该代码假设有一个书架,显然可以根据需要进行调整。它并不假设只有两个 bookshelf > book
元素,它列出了尽可能多的元素。
关于Java jdom不打印所有元素,打印空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53590862/