Java xml解析之JDom解析
程序员文章站
2022-05-30 09:48:23
...
该解析方法与dom4j解析 比较类似同样需要使用第三方jar包,大致有以下步骤:
1.创建SAXBuilder 对象。
SAXBuilder sax = new SAXBuilder();
2.通过SAXBuilder 对象创建文档对象
Documentdoc=sax.build(Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML/Student.xml"));
3.通过文件对象获取根节点
Element root = doc.getRootElement();
4.通过根节点可以得到其他节点以及属性进行相应操作
List<Element> children = root.getChildren();//获取跟节点下的子节点。返回List集合
例子:
1.创建XML文件
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student score="23">
<name>"张三"</name>
<id>1003</id>
<sex>女</sex>
</student>
<student score="24">
<name>"李四"</name>
<id>1004</id>
<sex>男</sex>
</student>
<student id="1005">
<name>"张五"</name>
<score>25</score>
<sex>男</sex>
</student>
</students>
2.创建Students对象:
public class Students {
private int id;
private int socre;
private String name;
private String sex;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getSocre() {
return socre;
}
public void setSocre(int socre) {
this.socre = socre;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Students [id=" + id + ", socre=" + socre + ", name=" + name + ", sex=" + sex + "]";
}
}
3.进行JDOM解析
package MyXMl;
import java.util.ArrayList;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.Namespace;
import org.jdom2.input.SAXBuilder;
//Jdom解析,需要使用第三方jar包
public class JDomparse {
public static void main(String[] args) throws Exception {
//加载文档
SAXBuilder sax = new SAXBuilder();
Document doc = sax.build(Thread.currentThread().getContextClassLoader().getResourceAsStream("MyXML/Student.xml"));
//直接获取文档的根节点
Element root = doc.getRootElement();
List<Element> children = root.getChildren();//获取跟节点下的子节点。返回List集合
List<Students> list = new ArrayList<Students>();
//遍历子节点
for(Element e:children) {
Students stu = new Students();
List<Attribute> att = e.getAttributes();//获取该节点的属性,返回一个集合
for(Attribute a:att) {
if("id".equals(a.getName())) {
stu.setId(Integer.parseInt(a.getValue()));//getValue()获取属性的值
}
if("sex".equals(a.getName())) {
stu.setSex(a.getValue());
}
if("score".equals(a.getName())) {
stu.setSocre(Integer.parseInt(a.getValue()));
}
if("name".equals(a.getName())) {
stu.setName(a.getValue());
}
}
List<Element> children2 = e.getChildren();//获取该节点下的子节点,返回list集合
for(Element e1:children2) {
if("id".equals(e1.getName())) {
stu.setId(Integer.parseInt(e1.getValue()));//getValue()获取属性的值
}
if("sex".equals(e1.getName())) {
stu.setSex(e1.getValue());
}
if("score".equals(e1.getName())) {
stu.setSocre(Integer.parseInt(e1.getValue()));
}
if("name".equals(e1.getName())) {
stu.setName(e1.getValue());
}
}
list.add(stu);
}
for(Students s:list) {
System.out.println(s);
}
}
}
运行结果: