Unmarshaller解析xml文件
2018-05-09 11:21 不痒不痛 阅读(2531) 评论(0) 编辑 收藏 举报参考地址:http://linbulu.iteye.com/blog/2295919
Girl.xml文件
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <root> <girl> <name>lily</name> <age>18</age> </girl> <girl> <name>lucy</name> <age>20</age> </girl> <girl> <name>lisa</name> <age>17</age> </girl> </root>
创建Girl.java类,另一种映射方法参考地址:https://blog.csdn.net/hongweigg/article/details/6764237
import java.util.List; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "root") public class Girl { @XmlElement(name = "name") private String name; @XmlElement(name = "age") private String age; @XmlElement(name = "girl") private List<Girl> girlList; public String toString() { StringBuilder sb = new StringBuilder(); for (Girl girl : girlList) { sb.append(girl.toString()); } return sb.toString(); } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Girl> getGirlList() { return girlList; } public void setGirlList(List<Girl> girlList) { this.girlList = girlList; } }
测试类
import java.io.File; import java.util.List; import javax.xml.bind.*; public class TestUnm { public static void main(String[] args) { try { File file=new File("E:\\app\\Girl.xml"); JAXBContext jaxbC = JAXBContext.newInstance(Girl.class); Unmarshaller us = jaxbC.createUnmarshaller(); Girl girl=(Girl)us.unmarshal(file); List<Girl> list=girl.getGirlList(); for(Girl ele:list){ System.out.println("name:"+ele.getName()); System.out.println("age:"+ele.getAge()); } } catch (Exception e) { e.printStackTrace(); } } }
控制台输出结果
name:lily age:18 name:lucy age:20 name:lisa age:17