Dom4j解析xml文件

it2024-12-10  15

Dom4j解析xml文件

1.导入需要用到的jar包

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输入流,去读取 xml配置文件,生成Document对象 //1. 读取Hero.xml文件 SAXReader reader = new SAXReader(); //在Junit测试中,相对路径是从模块名开始的 Document document = reader.read("05_xml/src/com/chunxi/xml/Hero.xml"); //2.通过Document对象获取根元素 Element rootElement = document.getRootElement(); //3.通过根元素获取hero标签对象 //element()和elements()都是通过标签名查找子元素 List<Element> heroes = rootElement.elements("Hero"); //4.遍历,处理每个hero标签转化为Hero类 for (Element hero:heroes ) { //asXML()把标签对象转化标签字符串 //System.out.println(hero.asXML()); Element elementName = hero.element("name"); //getText()可以获取标签中的文本内容 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.运行测试用例查看控制台

最新回复(0)