简体   繁体   中英

XML Parsing using DOM

I have an XML with the following data...

<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>

I want to parse this using JDOM parser in a servlet...I have used the following code so far:

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

    }

However my code returns values for the first child element of root repetitively 3 times. I assume this is because i have all 3 child name as "movie" only.

So i want to distinguish these, and make the count to next movie child with attributes like Title="par" etc..

Been figuring out this since so long but could not find. Help would be really appreciable

Your's is not working because even though you are looping 3 times, you are always fetching the same (first) node through:

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

Try this: (untested)

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

The best way is to get the attribute from the children list instead of asking for movieAtt again.

I have never used JDOM but my pseudocode would be as follows:

for (int i = 0; i < children.size(); i++) {
    Element e = children.get(i);
    String title = e.getAttributeValue("Title");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM