Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java jdom没有';t打印所有元素,打印空字符串_Java_Xml_Pom.xml_Element_Document - Fatal编程技术网

Java jdom没有';t打印所有元素,打印空字符串

Java jdom没有';t打印所有元素,打印空字符串,java,xml,pom.xml,element,document,Java,Xml,Pom.xml,Element,Document,首先,我有一个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<

首先,我有一个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>
我觉得很奇怪:

(1) 为什么打印的第一个元素是“b11”而不是“c01”?这是第一个元素

(2) 为什么只打印一个“book”元素,而另一个是空的


非常感谢。

这是因为嵌套的
标记。由于
内的
标记,解析器将
Oracle
视为第二条记录

 <book ISBN="c01" press="AD press">
        <book>Oracle</book> //<book> tag inside <book>
        <Author>Smith</Author>
        <price>32.00</price>
    </book>

Oracle//taginside
史密斯
32
(1) 为什么打印的第一个元素是“b11”而不是“c01”?这是第一个元素

对我来说,没有。我得到了
c01
,然后是一个空白条目,考虑到输入,这是有意义的

(2) 为什么只打印一个“book”元素,而另一个是空的

因为在其他
book
元素中有
book
元素
getElementsByTagName
返回所有四个参数。第二个是嵌套在第一个中的:


#1(索引0)
甲骨文#2(索引1)
史密斯
32
#3(索引2)
安卓4(索引3)
史密斯
35
我对这个特定的API不太熟悉,但是如果我得到
书架
,然后循环它的子项并选择那些是
的子项,我会得到预期的输出:

import javax.xml.parsers.*;
导入org.w3c.dom.*;
课例{
公共静态最终void main(字符串[]args)引发异常{
DocumentBuilderFactory工厂=DocumentBuilderFactory.newInstance();
DocumentBuilder=factory.newDocumentBuilder();
Document=builder.parse(“book.xml”);
NodeList bookshelfs=document.getElementsByTagName(“bookshelf”);
if(bookshelfs.getLength()>0){
元素书架f=(元素)书架。项(0);
nodelistchildrends=bookshelf.getChildNodes();
for(int i=0,l=children.getLength();i

该代码假设只有一个书架,显然可以根据需要进行修改。它不假定只有两个
bookshelf>book
元素,它列出了尽可能多的元素。

您的xml有点复杂,因为
表示两种不同的东西

我的建议是用
作为标题,而不是
来标记文档更具可读性


神谕
史密斯
32
安卓
史密斯
35
begin
b11
XY press
end
begin


end
 <book ISBN="c01" press="AD press">
        <book>Oracle</book> //<book> tag inside <book>
        <Author>Smith</Author>
        <price>32.00</price>
    </book>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<bookshelf>
    <book ISBN="c01" press="AD press">
        <title>Oracle</title>
        <Author>Smith</Author>
        <price>32.00</price>
    </book>
    <book ISBN="b11" press="XY press">
        <title>Android</title>
        <Author>Smith</Author>
        <price>35.00</price>
    </book>
</bookshelf>