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;
}
@XmlValue
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value.trim();
}
}