Unmarshaller解析xml文件
生活随笔
收集整理的這篇文章主要介紹了
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
轉載于:https://www.cnblogs.com/l412382979/p/9013156.html
總結
以上是生活随笔為你收集整理的Unmarshaller解析xml文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS6.5的安装及忘记root密
- 下一篇: ref:ThinkPHP Builder