JAXB解析XML
⾸先根据XML⽂件编写.xsd⽂件,例如:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns:tns=""
xmlns=""
targetNamespace=""
elementFormDefault="unqualified"
xmlns:jaxb=""
jaxb:version="2.0"
xmlns:xjc=""
jaxb:extensionBindingPrefixes="xjc">
<annotation>
<appinfo>
<jaxb:globalBindings>
<xjc:simple />
</jaxb:globalBindings>
</appinfo>
</annotation>
<element name="root">
<complexType>
<sequence>
<element name="config" maxOccurs="unbounded">
<complexType>
<attribute name="ip" type="string"></attribute>
<attribute name="sectionId" type="string"></attribute>
<attribute name="sectionName" type="string"></attribute>
<attribute name="collectId" type="string"></attribute>
<attribute name="collectName" type="string"></attribute>
xml文件怎么打开<attribute name="equipmentId" type="string"></attribute>
<attribute name="equipmentName" type="string"></attribute>
<attribute name="direction" type="string"></attribute>
</complexType>
</element>
</sequence>
</complexType>
</element>
</schema>
将.xsd⽂件编写完成之后,打开DOS窗⼝,将⽬录转到.xsd⽂件存放的⽬录,使⽤命令⽣成解析XML需要的Java类。命令如下:
xjc XXX.xsd -extension
⼀般会⽣成以下⼏个Java类:
ObjectFactory.java
package-info.java
Root.java
将⽣成的Java类放⼊⼯程所需的⽬录(根据⾃⼰的⼯程⽽定)。
然后使⽤JAXBContext等类解析XML即可,例如:
private static Map<String,Config> devidToIp=new HashMap<String,Config>();
static{
JAXBContext context;
try {
context = wInstance("com.hisense.fig");
Unmarshaller ateUnmarshaller();
Root root=(Root) um.unmarshal(ResourceAsStream("/l"));
for(Root.Config Configs()){
devidToIp.Ip(), config);
}
} catch (Exception e) {
<("初始化配置⽂件出现错误。", e);
} }