Dom4j解析xml文件
1.导入需要用到的jar包
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9e8851dfc494d2edeb9e11497e47d80a.png#pic_center)
2.创建测试所用的Hero类
public class Hero {
private String id;
private String name;
private double hp;
private double mp;
public Hero() {
}
public Hero(String id, String name, double hp, double mp) {
this.id = id;
this.name = name;
this.hp = hp;
this.mp = mp;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHp() {
return hp;
}
public void setHp(double hp) {
this.hp = hp;
}
public double getMp() {
return mp;
}
public void setMp(double mp) {
this.mp = mp;
}
@Override
public String toString() {
return "Hero{" +
"id=" + id +
", name='" + name + '\'' +
", hp=" + hp +
", mp=" + mp +
'}';
}
}
3.准备所需要解析的xml文件
<?xml version="1.0" encoding="utf-8" ?>
<Heroes>
<Hero id="0001">
<name>Talon</name>
<hp>550</hp>
<mp>300</mp>
</Hero>
<Hero id="0002">
<name>Jayce</name>
<hp>560</hp>
<mp>375</mp>
</Hero>
</Heroes>
4.编写测试用例
public class TestDom4j {
@Test
public void test(){
try {
SAXReader reader = new SAXReader();
Document document = reader.read("05_xml/src/com/chunxi/xml/Hero.xml");
Element rootElement = document.getRootElement();
List<Element> heroes = rootElement.elements("Hero");
for (Element hero:heroes
) {
Element elementName = hero.element("name");
String nameText = elementName.getText();
String hp = hero.elementText("hp");
String mp = hero.elementText("mp");
String id = hero.attributeValue("id");
System.out.println(new Hero(id,nameText,Double.parseDouble(hp),Double.parseDouble(mp)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.运行测试用例查看控制台
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/88b5ac0586bd561a9bd30eaf85b4b504.png#pic_center)