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);
  }
 }

 

转载于:https://www.cnblogs.com/wjwei1213/p/3604974.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值