gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:46:25 25 4
gpt4 key购买 nike

我正在使用 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();

}

}
}

请帮帮我。我是初学者,抱歉。

请建议我另一种方法。

谢谢

最佳答案

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 的返回值是 NodeList 或者,在在这种情况下,Element

关于java - 如何使用 jdom 获取子元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9759907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com