Java下3中XML解析 DOM方式、SAX方式和StAX方式

先简单说下前三种方式:

DOM方式:个人理解类似.net的XmlDocument,解析的时候效率不高,占用内存,不适合大XML的解析;
SAX方式:基于事件的解析,当解析到xml的某个部分的时候,会触发特定事件,可以在自定义的解析类中定义当事件触发时要做得事情;个人感觉一种很另类的方式,不知道.Net体系下是否有没有类似的方式?
StAX方式:个人理解类似.net的XmlReader方式,效率高,占用内存少,适用大XML的解析;
不过SAX方式之前也用过,本文主要介绍JAXB,这里只贴下主要代码:

代码如下:

import java.util.ArrayList;

import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ConfigParser extends DefaultHandler {
    private String currentConfigSection;
     public SysConfigItem sysConfig;
     public List<InterfaceConfigItem> interfaceConfigList;
     public List<FtpConfigItem> ftpConfigList;
     public List<AdapterConfigItem> adapterConfigList;
     public void startDocument() throws SAXException {
         sysConfig = new SysConfigItem();
         interfaceConfigList = new ArrayList<InterfaceConfigItem>();
         ftpConfigList = new ArrayList<FtpConfigItem>();
         adapterConfigList = new ArrayList<AdapterConfigItem>();
     }
     public void endDocument() throws SAXException {
     }
     public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
         if (qName.equalsIgnoreCase("Item") && attributes.getLength() > 0) {
             if (currentConfigSection.equalsIgnoreCase("SysConfigItem")) {
                 sysConfig = new SysConfigItem(attributes);
             } else if (currentConfigSection.equalsIgnoreCase("InterfaceConfigItems")) {
                 interfaceConfigList.add(new InterfaceConfigItem(attributes));
             } else if (currentConfigSection.equalsIgnoreCase("FtpConfigItems")) {
                 ftpConfigList.add(new FtpConfigItem(attributes));
             } else if (currentConfigSection.equalsIgnoreCase("AdapterConfigItems")) {
                 adapterConfigList.add(new AdapterConfigItem(attributes));
             }
         } else {
             currentConfigSection = qName;
         }
     }
     public void endElement(String uri, String localName, String qName) throws SAXException {
     }
     public void characters(char ch[], int start, int length) throws SAXException {
     }
 }

代码如下:

import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.xml.sax.Attributes;
public class ConfigItemBase {
  private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  public ConfigItemBase() {
  }
  /**
   * 目前只支持几种常用类型 如果需要支持其他类型,请修改这里的代码
   *
   * @param attributes
   */
  public ConfigItemBase(Attributes attributes) {
      Class<?> cls = this.getClass();
      Field[] fields = cls.getDeclaredFields();
      for (Field field : fields) {
          String fieldType = field.getType().getSimpleName();
          for (int i = 0; i < attributes.getLength(); i++) {
              if (attributes.getQName(i).equalsIgnoreCase(field.getName())) {
                  field.setAccessible(true);
                  try {
                      if (fieldType.equalsIgnoreCase("String")) {
                          field.set(this, attributes.getValue(attributes.getQName(i)));
                      } else if (fieldType.equalsIgnoreCase("Integer")) {
                          field.set(this, Integer.valueOf(attributes.getValue(attributes.getQName(i))));
                      } else if (fieldType.equalsIgnoreCase("Double")) {
                          field.set(this, Double.valueOf(attributes.getValue(attributes.getQName(i))));
                      } else if (fieldType.equalsIgnoreCase("Date")) {
                          field.set(this, GetDate(attributes.getValue(attributes.getQName(i))));
                      } else {
                          System.out.println("Warning:Unhandler Field(" + field.getName() + "-" + fieldType + ")");
                      }
                  } catch (IllegalArgumentException e) {
                      e.printStackTrace();
                  } catch (IllegalAccessException e) {
                      e.printStackTrace();
                  }
                  break;
              }
          }
      }
  }
  public String toString() {
      String result = "";
      Class<?> cls = this.getClass();
      String classNameString = cls.getName();
      result += classNameString.substring(classNameString.lastIndexOf('.') + 1, classNameString.length()) + ":";
      Field[] fields = cls.getDeclaredFields();
      for (Field field : fields) {
          try {
              result += field.getName() + "=" + field.get(this) + ";";
          } catch (IllegalArgumentException e) {
              e.printStackTrace();
          } catch (IllegalAccessException e) {
              e.printStackTrace();
          }
      }
      return result;
  }
  /**
   * 处理时间类型属性(时间格式要求为:yyyy-MM-dd hh:mm:ss)
   *
   * @param dateString
   * @return
   */
  private static Date GetDate(String dateString) {
      Date date = null;
      try {
          date = dateFormat.parse(dateString);
      } catch (ParseException e) {
          e.printStackTrace();
      }
      return date;
  }
}

下面重点介绍一下最方便的:JAXB(Java Architecture for XML Binding)

这里用比较复杂的移动BatchSyncOrderRelationReq接口XML做为示例(感觉能解这个大家基本上够用了),报文格式如下(SvcCont里的CDATA内容是报文体,太恶心了):


代码如下:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<InterBOSS>
  <Version>0100</Version>
  <TestFlag>0</TestFlag>
  <BIPType>
      <BIPCode>BIP2B518</BIPCode>
      <ActivityCode>T2101518</ActivityCode>
      <ActionCode>0</ActionCode>
  </BIPType>
  <RoutingInfo>
      <OrigDomain>BOSS</OrigDomain>
      <RouteType>routeType</RouteType>
      <Routing>
          <HomeDomain>XXXX</HomeDomain>
          <RouteValue>routeValue</RouteValue>
      </Routing>
  </RoutingInfo>
  <TransInfo>
      <SessionID>2013041017222313925676</SessionID>
      <TransIDO>2013041017222313925676</TransIDO>
      <TransIDOTime>20130410172223</TransIDOTime>
      <TransIDH></TransIDH>
      <TransIDHTime></TransIDHTime>
  </TransInfo>
  <SNReserve>
      <TransIDC></TransIDC>
      <ConvID></ConvID>
      <CutOffDay></CutOffDay>
      <OSNTime></OSNTime>
      <OSNDUNS></OSNDUNS>
      <HSNDUNS></HSNDUNS>
      <MsgSender></MsgSender>
      <MsgReceiver></MsgReceiver>
      <Priority></Priority>
      <ServiceLevel></ServiceLevel>
      <SvcContType></SvcContType>
  </SNReserve>
  <Response>
      <RspType>rspType</RspType>
      <RspCode>rspCode</RspCode>
      <RspDesc>rspDesc</RspDesc>
  </Response>
  <SvcCont><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<batchSyncOrderRelationReq>
  <msgTransactionID>210001BIP2B518130410172223651627</msgTransactionID>
  <reqNum>2</reqNum>
  <reqBody>
      <oprNumb>210001BIP2B518130410172224341871</oprNumb>
      <subscriptionInfo>
          <oprTime>oprTime1</oprTime>
          <actionID>actionId1</actionID>
          <brand>brand1</brand>
          <effTime>effTime1</effTime>
          <expireTime>expireTime1</expireTime>
          <feeUser_ID>feeUserId1</feeUser_ID>
          <destUser_ID>destUserId1</destUser_ID>
          <actionReasonID>actionId1</actionReasonID>
          <servType>servType1</servType>
          <subServType>subServType1</subServType>
          <SPID>spId1</SPID>
          <SPServID>spServId1</SPServID>
          <accessMode>accessMode1</accessMode>
          <servParamInfo>
              <para_num>0</para_num>
              <para_info>
                  <para_name></para_name>
                  <para_value></para_value>
              </para_info>
          </servParamInfo>
          <feeType>feeType1</feeType>
      </subscriptionInfo>
  </reqBody>
  <reqBody>
      <oprNumb>210001BIP2B518130410172224420909</oprNumb>
      <subscriptionInfo>
          <oprTime>oprTime2</oprTime>
          <actionID>actionId2</actionID>
          <brand>brand2</brand>
          <effTime>effTime2</effTime>
          <expireTime>expireTime2</expireTime>
          <feeUser_ID>feeUserId2</feeUser_ID>
          <destUser_ID>destUserId2</destUser_ID>
          <actionReasonID>actionId2</actionReasonID>
          <servType>servType2</servType>
          <subServType>subServType2</subServType>
          <SPID>spId2</SPID>
          <SPServID>spServId2</SPServID>
          <accessMode>accessMode2</accessMode>
          <servParamInfo>
              <para_num>0</para_num>
              <para_info>
                  <para_name></para_name>
                  <para_value></para_value>
              </para_info>
          </servParamInfo>
          <feeType>feeType2</feeType>
      </subscriptionInfo>
  </reqBody>
</batchSyncOrderRelationReq>]]></SvcCont>
</InterBOSS>

解码代码如下:


代码如下:

@XmlRootElement(name = "batchSyncOrderRelationReq")

@XmlAccessorType(XmlAccessType.FIELD)
 public class BatchSyncOrderRelationReq extends BossMessage<BatchSyncOrderRelationReq> {
     @XmlElement(name = "msgTransactionID")
     private String msgTransactionId = "";
     @XmlElement(name = "reqNum")
     private String reqNum = "";
    @XmlElement(name = "reqBody")
    private List<BatchSyncOrderRelationReqBody> reqBodyList;
    public BatchSyncOrderRelationReq() {
    }
    public String getMsgTransactionId() {
        return this.msgTransactionId;
    }
    public void setMsgTransactionId(String msgTransactionId) {
        this.msgTransactionId = msgTransactionId;
    }
    public String getReqNum() {
        return this.reqNum;
    }
    public void setReqNum(String reqNum) {
        this.reqNum = reqNum;
    }
    public List<BatchSyncOrderRelationReqBody> getReqBodyList() {
        return this.reqBodyList;
    }
    public void setReqBodyList(List<BatchSyncOrderRelationReqBody> reqBodyList) {
        this.reqBodyList = reqBodyList;
    }
     @Override
     public BatchSyncOrderRelationReq Deserialized(String interBossXmlContent) throws BusinessException {
         try {
             // deserialized for head
             JAXBContext jaxbCxt4Head = JAXBContext.newInstance(MessageHead.class);
             Unmarshaller unmarshaller4Head = jaxbCxt4Head.createUnmarshaller();
             MessageHead head = (MessageHead) unmarshaller4Head.unmarshal(new StringReader(interBossXmlContent));
             // deserialized for SyncOrderRelationReq body
             JAXBContext jaxbCxt4Body = JAXBContext.newInstance(BatchSyncOrderRelationReq.class);
             Unmarshaller unmarshaller4Body = jaxbCxt4Body.createUnmarshaller();
             BatchSyncOrderRelationReq batchSyncOrderRelationReq = (BatchSyncOrderRelationReq) unmarshaller4Body.unmarshal(new StringReader(head.getSvcCont().trim()));
             batchSyncOrderRelationReq.setHead(head);
             return batchSyncOrderRelationReq;
         } catch (JAXBException e) {
             throw new BusinessException("SyncOrderRelationReq.Deserialized() Error!(" + interBossXmlContent + ")", e);
         }
     }
 }

@XmlAccessorType(XmlAccessType.FIELD)


代码如下:

public class BatchSyncOrderRelationReqBody {
  @XmlElement(name = "oprNumb")
  private String oprNumb = "";
  @XmlElement(name = "subscriptionInfo")
  private SubscriptionInfo subscriptionInfo;
  public BatchSyncOrderRelationReqBody(){
  }
  public BatchSyncOrderRelationReqBody(String oprNumb, SubscriptionInfo subscriptionInfo) {
      this.oprNumb = oprNumb;
      this.subscriptionInfo = subscriptionInfo;
  }
  public String getOprNumb() {
      return this.oprNumb;
  }
  public void setOprNumb(String oprNumb) {
      this.oprNumb = oprNumb;
  }
  public SubscriptionInfo getSubscriptionInfo() {
      return this.subscriptionInfo;
  }
  public void setSubscriptionInfo(SubscriptionInfo subscriptionInfo) {
      this.subscriptionInfo = subscriptionInfo;
  }
}

@XmlAccessorType(XmlAccessType.FIELD)


代码如下:

public class SubscriptionInfo {
  @XmlElement(name = "oprTime")
  private String oprTime = "";
  @XmlElement(name = "actionID")
  private String actionId = "";
  @XmlElement(name = "brand")
  private String brand = "";
  @XmlElement(name = "effTime")
  private String effTime = "";
  @XmlElement(name = "expireTime")
  private String expireTime = "";
  @XmlElement(name = "feeUser_ID")
  private String feeUserId = "";
  @XmlElement(name = "destUser_ID")
  private String destUserId = "";
  @XmlElement(name = "actionReasonID")
  private String actionReasonId = "";
  @XmlElement(name = "servType")
  private String servType = "";
  @XmlElement(name = "subServType")
  private String subServType = "";
  @XmlElement(name = "SPID")
  private String spId = "";
  @XmlElement(name = "SPServID")
  private String spServId = "";
  @XmlElement(name = "accessMode")
  private String accessMode = "";
  @XmlElement(name = "feeType")
  private String feeType = "";
  public SubscriptionInfo() {
  }
  public SubscriptionInfo(
          String oprTime,
          String actionId,
          String brand,
          String effTime,
          String expireTime,
          String feeUserId,
          String destUserId,
          String actionReasonId,
          String servType,
          String subServType,
          String spId,
          String spServId,
          String accessMode,
          String feeType) {
      this.oprTime = oprTime;
      this.actionId = actionId;
      this.brand = brand;
      this.effTime = effTime;
      this.expireTime = expireTime;
      this.feeUserId = feeUserId;
      this.destUserId = destUserId;
      this.actionReasonId = actionReasonId;
      this.servType = servType;
      this.subServType = subServType;
      this.spId = spId;
      this.spServId = spServId;
      this.accessMode = accessMode;
      this.feeType = feeType;
  }
  public String getOprTime() {
      return this.oprTime;
  }
  public void setOprTime(String oprTime) {
      this.oprTime = oprTime;
  }
  public String getActionId() {
      return this.actionId;
  }
  public void setActionId(String actionId) {
      this.actionId = actionId;
  }
  public String getBrand() {
      return this.brand;
  }
  public void setBrand(String brand) {
      this.brand = brand;
  }
  public String getEffTime() {
      return this.effTime;
  }
  public void setEffTime(String effTime) {
      this.effTime = effTime;
  }
  public String getExpireTime() {
      return this.expireTime;
  }
  public void setExpireTime(String expireTime) {
      this.expireTime = expireTime;
  }
  public String getFeeUserId() {
      return this.feeUserId;
  }
  public void setFeeUserId(String feeUserId) {
      this.feeUserId = feeUserId;
  }
  public String getDestUserId() {
      return this.destUserId;
  }
  public void setDestUserId(String destUserId) {
      this.destUserId = destUserId;
  }
  public String getActionReasonId() {
      return this.actionReasonId;
  }
  public void setActionReasonId(String actionReasonId) {
      this.actionReasonId = actionReasonId;
  }
  public String getServType() {
      return this.servType;
  }
  public void setServType(String servType) {
      this.servType = servType;
  }
  public String getSubServType() {
      return this.subServType;
  }
  public void setSubServType(String subServType) {
      this.subServType = subServType;
  }
  public String getSpId() {
      return this.spId;
  }
  public void setSpId(String spId) {
      this.spId = spId;
  }
  public String getSpServId() {
      return this.spServId;
  }
  public void setSpServId(String spServId) {
      this.spServId = spServId;
  }
  public String getAccessMode() {
      return this.accessMode;
  }
  public void setAccessMode(String accessMode) {
      this.accessMode = accessMode;
  }
  public String getFeeType() {
      return this.feeType;
  }
  public void setFeeType(String feeType) {
      this.feeType = feeType;
  }
}

(0)

相关推荐

  • Java中使用DOM和SAX解析XML文件的方法示例

    dom4j介绍 dom4j的项目地址:http://sourceforge.net/projects/dom4j/?source=directory dom4j是一个简单的开源库,用于处理XML. XPath和XSLT,它基于Java平台,使用Java的集合框架,全面集成了DOM,SAX和JAXP. dom4j的使用 下载了dom4j项目之后,解压缩,将其jar包(我的当前版本叫做dom4j-1.6.1.jar)加入class path下面. (Properties->Java Build Pa

  • java中使用sax解析xml的解决方法

    在java中,原生解析xml文档的方式有两种,分别是:Dom解析和Sax解析 Dom解析功能强大,可增删改查,操作时会将xml文档以文档对象的方式读取到内存中,因此适用于小文档 Sax解析是从头到尾逐行逐个元素读取内容,修改较为不便,但适用于只读的大文档 本文主要讲解Sax解析,其余放在后面 Sax采用事件驱动的方式解析文档.简单点说,如同在电影院看电影一样,从头到尾看一遍就完了,不能回退(Dom可来来回回读取) 在看电影的过程中,每遇到一个情节,一段泪水,一次擦肩,你都会调动大脑和神经去接收或

  • Sax解析xml_动力节点Java学院整理

    JAVA 解析 XML 通常有两种方式,DOM 和 SAX.DOM 虽然是 W3C 的标准,提供了标准的解析方式,但它的解析效率一直不尽如人意,因为使用DOM解析XML时,解析器读入整个文档并构建一个驻留内存的树结构(节点树),然后您的代码才可以使用 DOM 的标准接口来操作这个树结构.但大部分情况下我们只对文档的部分内容感兴趣,根本就不用先解析整个文档,并且从节点树的根节点来索引一些我们需要的数据也是非常耗时的. SAX是一种XML解析的替代方法.相比于文档对象模型DOM,SAX 是读取和操作

  • java解析xml之sax解析xml示例分享

    复制代码 代码如下: package com.test; import java.io.File;import java.io.FileInputStream;import java.util.ArrayList;import java.util.List; import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes;import org.x

  • Java下3中XML解析 DOM方式、SAX方式和StAX方式

    先简单说下前三种方式: DOM方式:个人理解类似.net的XmlDocument,解析的时候效率不高,占用内存,不适合大XML的解析:SAX方式:基于事件的解析,当解析到xml的某个部分的时候,会触发特定事件,可以在自定义的解析类中定义当事件触发时要做得事情:个人感觉一种很另类的方式,不知道.Net体系下是否有没有类似的方式?StAX方式:个人理解类似.net的XmlReader方式,效率高,占用内存少,适用大XML的解析:不过SAX方式之前也用过,本文主要介绍JAXB,这里只贴下主要代码: 复

  • Java使用Jdom读取xml解析实例

    本文实例讲述了Java使用Jdom读取xml解析.分享给大家供大家参考,具体如下: package com.yanek.demo.xml.test; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMExcep

  • c#中XML解析文件出错解决方法

    1.内容中含有xml预定好的实体,如"<"和"&",对xml来说是禁止使用的,针对这种字符,解决方式是使用CDATA部件以"<![CDATA[" 标记开始,以"]]>"标记结束,是CDATA内部内容被解析器忽略.具体说明参考<XML CDATA是什么?>. 2.内容中含有低位非打印字符,解析时会报错:""(十六进制值 0x1D)是无效的字符.加载或保存XML时引发的异常

  • iOS之数据解析之XML解析详解

    XML解析常见的两种方式:DOM解析和SAX解析 DOM解析 DOM:Document Object Model(文档对象类型).解析XML时,读入整个XML文档并构建一个驻留内存的树结构(节点树),通过遍历数结构可以检索任意XML节点,读取它的属性和值,而且通常情况下,可以借助XPath,直接查询XML节点. 进行DOM方式解析数据需要使用一个第三方的类GDataXMLNode GDataXMLNode是Google提供的开源XML解析类,对libxml2.tbd进行了Objective-C的

  • iOS开发使用XML解析网络数据

    前言:本篇随笔介绍的是XML解析. 正文: 1.XML解析方式有2两种: DOM:一次性将整个XML数据加载进内存进行解析,比较适合解析小文件SAX:从根元素开始,按顺序一个元素一个元素往下解析,比较适合解析大文件 2.IOS中XML解析方案有很多种: 2-1.第三方框架: libxml2:纯C语言,默认包含在iOS SDK中,同时支持DOM和SAX解析 GDataXML:DOM方式解析,由Google开发,基于libxml2 2-2.苹果原生 NSXMLParser:SAX方式解析,使用简单

  • java操作(DOM、SAX、JDOM、DOM4J)xml方式的四种比较与详解

    1)DOM(JAXP Crimson解析器) DOM是用与平台和语言无关的方式表示XML文档的官方W3C标准.DOM是以层次结构组织的节点或信息片断的集合.这个层次结构允许开发人员在树中寻找特定信息.分析该结构通常需要加载整个文档和构造层次结构,然后才能做任何工作.由于它是基于信息层次的,因而DOM被认为是基于树或基于对象的.DOM以及广义的基于树的处理具有几个优点.首先,由于树在内存中是持久的,因此可以修改它以便应用程序能对数据和结构作出更改.它还可以在任何时候在树中上下导航,而不是像SAX那

  • Java中四种XML解析技术

    在平时工作中,难免会遇到把 XML 作为数据存储格式.面对目前种类繁多的解决方案,哪个最适合我们呢?在这篇文章中,我对这四种主流方案做一个不完全评测,仅仅针对遍历 XML 这块来测试,因为遍历 XML 是工作中使用最多的(至少我认为). 预 备 测试环境: AMD 毒龙1.4G OC 1.5G.256M DDR333.Windows2000 Server SP4.Sun JDK 1.4.1+Eclipse 2.1+Resin 2.1.8,在 Debug 模式下测试. XML 文件格式如下: <?

  • Android解析XML的三种方式SAX、Pull、Dom

    在android开发中,经常用到去解析xml文件,常见的解析xml的方式有一下三种:SAX.Pull.Dom解析方式.最近做了一个android版的CSDN阅读器,用到了其中的两种(sax,pull),本文对android解析xml的这三种方式进行一次总结. 今天解析的xml示例(channels.xml)如下: <?xml version="1.0" encoding="utf-8"?> <channel> <item id=&quo

  • java中xml进行报文发送和解析操作

    利用OKhttp网络框架,进行Maven项目管理 //报文发送 <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.8.0</version> </dependency> //报文解析 <dependency> <groupId>xom</gr

随机推荐