java - 使用 DOM 进行 XML 解析

标签 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="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" ));
        }   

    }

但是我的代码重复返回 root 的第一个子元素的值 3 次。我认为这是因为我的三个 child 的名字都只是“电影”。

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

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

最佳答案

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

Element movieAtt = doc.getRootElement().getChild("movie"); 

试试这个: (未经测试)

    Element root = doc.getRootElement();
    List children = root.getChildren();     
    out.println(root);  
    if (children != null)
    {
       for (Element child : children) 
       {
         out.println(child.getAttributeValue( "Title" ));
       }
    } 

关于java - 使用 DOM 进行 XML 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8036276/

相关文章:

java - Primefaces 数据表中的确认对话框问题

android - 如何解决 xamarin 中的 'Theme.AppCompat.Light.NoActionBar' 错误?

Android:更改设备设置时的布局大小问题

xml - 如何使用 XML::Compile::WSDL11 添加任意字段(错误:标记 `param' 未使用...)

json - Alamofire 4.0 JSOn 解析 Swift

java - 解析java中具有相同开头但不同结尾的字符串

java - JScrollPane 正在改变它的大小

java - Maven surefire 找不到 ForkedBooter 类

java - java中的 "invoking a static method with class name"和 "invoking a static method with an object"有什么区别吗?

java - 在预煮中使用变量