Unmarshaller解析xml文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unmarshaller解析xml文件相关的知识,希望对你有一定的参考价值。
参考地址: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
以上是关于Unmarshaller解析xml文件的主要内容,如果未能解决你的问题,请参考以下文章
java 关于 javax.xml.bind.Unmarshaller 根据xml反射对象的的问题
XML与Java之间相互转换(1.Java对象转换成XML(Marshaller) 2.XML转换成java对象(Unmarshaller) )