JAXB解析XML

首先根据XML文件编写.xsd文件,例如:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns:tns="www.hisense.com"
 xmlns="http://www.w3.org/2001/XMLSchema"
 targetNamespace="www.hisense.com"
 elementFormDefault="unqualified"
 xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
 jaxb:version="2.0"
   xmlns:xjc="http://java.sun.com/xml/ns/jaxb/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>
      <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 = JAXBContext.newInstance("com.hisense.adapter.microwave.config");
   Unmarshaller um=context.createUnmarshaller();
   Root root=(Root) um.unmarshal(MicrowaveManager.class.getResourceAsStream("/microwaveconfig.xml"));
   for(Root.Config config:root.getConfigs()){
    devidToIp.put(config.getIp(), config);
   }
  } catch (Exception e) {
   log.error("初始化配置文件出现错误。", e);
  }
 }

 

posted @ 2014-03-17 14:18  沉默不语  阅读(1127)  评论(0编辑  收藏  举报