欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java JDom 解析xml

程序员文章站 2022-05-28 10:51:59
...
JDOM在解析XML在代码量之上比之前的方法(DOM和SAX要少很多了)。

XML文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<Students>
<student>
<NO id="123">123456</NO>
<NAME>abc</NAME>
</student>
<student>

<NO id="234">456789</NO>
<NAME>def</NAME>
</student>
</Students>


代码如下:

public static void main(String args[]) throws JDOMException, IOException{
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new File("D:"+File.separator+"test.xml"));
Element foo = doc.getRootElement();
List allChildren = foo.getChildren();
for(int i=0;i<allChildren.size();i++) {
System.out.print("NO:" + ((Element)allChildren.get(i)).getChild("NO").getText());
System.out.print("\tid:"+((Element)allChildren.get(i)).getChild("NO").getAttributeValue("id"));
System.out.println("\tAddress:" + ((Element)allChildren.get(i)).getChild("NAME").getText());
}
}
相关标签: java jdom jdom xml