yashmathur
yashmathur

Reputation: 65

How do I get the child element's attributes using jdom

Im creating application in java using XML.

XML-

<?xml version="1.0" encoding="UTF-8"?>
<songlist id="slist">
  <song name="Club Can't Handle Me" path="E:/Google Chrome Downloads/club cant handle me.mp3" artist="Flo Rida feat. David Guetta" album="The Only One" />
  <song name="Call It What You Want" artist="Foster the People" path="E:\Google Chrome Downloads\call it what you want.mp3" album="Torches" />
  <song name="Break Your Heart (Remix) Ft. Ludacris" artist="Taio Cruz" path="E:\Google Chrome Downloads\Break your heart.mp3" album="Rockstarr" />
  <song name="Burn It To The Ground" artist="Nickelback" path="E:\Google Chrome Downloads\Burn It To The Ground.mp3" album="Dark Horse" />
  <song name="Levels" artist="Avicii" path="E:\Google Chroome Downloads\Avicii - Levels.mp3" album="" />
  <song name="Beautiful" artist="Akon" path="E:\Google Chrome Downloads\Beautiful.mp3" album="http://www.urbanascor.com" />
  <song name="Bumpy Ride" artist="" path="E:\Google Chrome Downloads\bumpy ride.mp3" album="" />
</songlist>

Im trying to get the attributes of the child elements(song), but im unable to do that. Im using JDOM.

Java code-

public class Opener extends WindowAdapter{
        @Override public void windowOpened(WindowEvent e){
            try{
            SAXBuilder builder = new SAXBuilder();
            File xmlFile = new File("E:/Yash programs/mp3/list.xml");
            Document doc = (Document) builder.build(xmlFile);
            Element rootNode = doc.getRootElement();
            List l = rootNode.getChildren();
            for(int i = 1;i<=l.size();i++){
                listModel.addElement(l.get(i).toString());
            }
        }
            catch (JDOMException ex) {
                Logger.getLogger(MP3View.class.getName()).log(Level.SEVERE, null, ex);
            }        
            catch(IOException io){
            io.printStackTrace();

        }

        }
    }

Please help me. Im a beginner ,sorry.

Please suggest me another way in which I can do this.

Thanks

Upvotes: 3

Views: 8924

Answers (1)

skaffman
skaffman

Reputation: 403581

List songElements = doc.getRootElement().getChildren("song");

for(int i = 1 ; i <= songElements.size() ; i++) {
   Element songElement = (Element) songElements.get(i);
   String name = songElement.getAttributeValue("name");
   String path = songElement.getAttributeValue("path");
   String album = songElement.getAttributeValue("album");
}

JDOM's collections are untyped, so you need to know that the return value of rootNode.getChildren is a List of Node or, in this case, Element.

Upvotes: 2

Related Questions