java利用jdom解析xml文件
程序员文章站
2022-05-30 09:56:28
...
说明:这只是一个简单的利用jdom解析xml文件的例子,读者可以下载附件的xml样例文件
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
public class ReadXml {
public static void main(String[] args) {
readXML();
}
private static void readXML(){
//创建一个
SAXBuilder builder=new SAXBuilder();
try {
//获取xml文件
Document doc=builder.build(new File("data.xml"));
//取得xml文件的根节点
Element rootElt=(Element)doc.getRootElement();
List eltList=XPath.selectNodes(rootElt,"//artist/catalog");
Iterator iter=eltList.iterator();
while(iter.hasNext()){
Element catalog=(Element)iter.next();
System.out.println("catalog_name:"+catalog.getChild("name").getText());
System.out.println("alias:"+catalog.getChild("alias").getText());
List items=catalog.getChildren("item");
if(items!=null){
readCatalogItemAndMaterial(items);
}
List materials=catalog.getChildren("material");
if(materials!=null){
readCatalogItemAndMaterial(materials);
}
}
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readCatalogItemAndMaterial(List list){
Iterator iter=list.iterator();
while(iter.hasNext()){
Element elt=(Element)iter.next();
System.out.println(elt.getChild("name").getText());
}
}
}