JAXB:XML to JavaBean

来源:互联网 发布:中国的中产阶级 知乎 编辑:程序博客网 时间:2024/05/16 15:15

Config.xml

<?xml version="1.0" encoding="UTF-8"?><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/config" xmlns="http://www.example.org/config" elementFormDefault="qualified"><xsd:element name="config">    <xsd:complexType>    <xsd:sequence>    <xsd:element name="case" maxOccurs="unbounded" minOccurs="0">                    <xsd:complexType>                    <xsd:attribute name="name" type="xsd:string" use="required"></xsd:attribute>                    </xsd:complexType>    </xsd:element>    </xsd:sequence>    </xsd:complexType>     </xsd:element></xsd:schema>

<config xmlns="http://www.example.org/config"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.example.org/config http://www.example.org/config/schema/config.xsd"><case name="case1">case1 content</case><case name="case2">case2 content</case></config>

主体对应配置类

package com.test;import java.io.InputStream;import java.util.List;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Unmarshaller;import javax.xml.bind.annotation.XmlElement;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElement(name="config", namespace=Config.NS)public class Config {public final static String NS = "http://www.example.org/config";private List<Case> caseList;@XmlElement(name="case", namespace=Config.NS)public List<Case> getCaseList() {return caseList;}public void setCaseList(List<Case> caseList) {this.caseList = caseList;}public static Config loadConfig(InputStream inStream)  {           try {              JAXBContext jaxbContext = JAXBContext.newInstance(Config.class);              Unmarshaller um = jaxbContext.createUnmarshaller();            return Config.class.cast(um.unmarshal(inStream));          } catch (JAXBException e) {              throw new RuntimeException(e);         } }public static void main(String[] args) {Config config = Config.loadConfig(Config.class.getResourceAsStream("config.xml"));for(Case curCase : config.getCaseList()) {System.out.println(curCase.getName() + ": " + curCase.getValue());}}}

子元素对应类

package com.test;import javax.xml.bind.annotation.XmlAttribute;import javax.xml.bind.annotation.XmlValue;public class Case {private String name;private String value;@XmlAttribute(name="name")public String getName() {return name;}public void setName(String name) {this.name = name;}@XmlValuepublic String getValue() {return value;}public void setValue(String value) {this.value = value.trim();}}


0 0
原创粉丝点击