gpt4 book ai didi

Java jdom 不打印所有元素,打印空字符串

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:02 25 4
gpt4 key购买 nike

首先,我有 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 然后循环它的 child 并挑选出那些是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com