码迷,mamicode.com
首页 > 其他好文 > 详细

Unmarshaller解析xml文件

时间:2018-05-09 15:08:01      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:https   oid   输出   csdn   sso   class   控制台   测试   结果   

参考地址: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文件

标签:https   oid   输出   csdn   sso   class   控制台   测试   结果   

原文地址:https://www.cnblogs.com/l412382979/p/9013156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!