如何使用jdom获取子元素的属性

时间:2012-03-18 16:19:35

标签: java jdom

我使用XML在java中创建应用程序。

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>

我试图获取子元素(歌曲)的属性,但我无法做到这一点。我正在使用JDOM。

Java代码 -

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();

        }

        }
    }

请帮帮我。我是初学者,对不起。

请以另一种方式建议我这样做。

由于

1 个答案:

答案 0 :(得分:1)

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的集合是无类型的,因此您需要知道rootNode.getChildren的返回值是List的{​​{1}},或者在这种情况下,Node