Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/334.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 使用DOM解析XML_Java_Xml_Parsing_Jdom - Fatal编程技术网

Java 使用DOM解析XML

Java 使用DOM解析XML,java,xml,parsing,jdom,Java,Xml,Parsing,Jdom,我有一个包含以下数据的XML <movies total="3"> <movie cover="9_pro.jpg" Title="A Very " MovieDuration="1.29" showtime="2:50 PM" theatre="UV3"/> <movie cover="5_pro.jpg" Title="Par" MovieDuration="1.24" showtime=" 12:00 PM" theatre="Uni

我有一个包含以下数据的XML

<movies total="3"> 
<movie cover="9_pro.jpg" Title="A Very " MovieDuration="1.29" showtime="2:50 PM"         theatre="UV3"/>
<movie cover="5_pro.jpg" Title="Par" MovieDuration="1.24" showtime=" 12:00 PM"     theatre="University Village 3"/>
<movie cover="8_pro.jpg" Title="PinBts" MovieDuration="1.30" showtime="9:20 PM" theatre="University Village 3"/>
</movies>

我想在servlet中使用JDOM解析器解析它……到目前为止,我已经使用了以下代码:

    try 
    {
    doc=builder.build(url);     
    Element root = doc.getRootElement();
    List children = root.getChildren();     
    out.println(root);  

    for (int i = 0; i < children.size(); i++) 
        {
            Element movieAtt = doc.getRootElement().getChild("movie");      
            //out.println(movieAtt.getAttributeValue( "cover" ));
            out.println(movieAtt.getAttributeValue( "Title" ));
            //out.println(movieAtt.getAttributeValue( "MovieDuration" ));
            //out.println(movieAtt.getAttributeValue( "showtime" ));
            //out.println(movieAtt.getAttributeValue( "theatre" ));
        }   

    }
试试看
{
doc=builder.build(url);
元素根=doc.getRootElement();
List children=root.getChildren();
out.println(根);
对于(int i=0;i
但是,我的代码重复3次返回root的第一个子元素的值。我想这是因为我只有3个孩子的名字作为“电影”

所以我想区分这些,并使用Title=“par”等属性对下一个电影子级进行计数


很久以来一直在想这个问题,但找不到。帮助将非常有用

因为即使循环3次,也总是通过以下方式获取相同(第一个)节点:

Element movieAtt = doc.getRootElement().getChild("movie"); 
试试这个: (未经测试)


最好的方法是从
children
列表中获取属性,而不是再次请求
movieAtt

我从未使用过JDOM,但我的伪代码如下:

for (int i = 0; i < children.size(); i++) {
    Element e = children.get(i);
    String title = e.getAttributeValue("Title");
}
for(int i=0;i
请注意,您可能需要将您的
列表子项
强制转换为
元素的列表。它工作于Element movieAtt=(Element)doc.getRootElement().getChildren(“movie”).get(i);您可以编写一个简单的助手类来完成围绕DOM的任务。看到这个了吗
for (int i = 0; i < children.size(); i++) {
    Element e = children.get(i);
    String title = e.getAttributeValue("Title");
}