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

2016-02-19 10:33 45 1 收藏

给自己一点时间接受自己,爱自己,趁着下午茶的时间来学习图老师推荐的Java下3中XML解析 DOM方式、SAX方式和StAX方式,过去的都会过去,迎接崭新的开始,释放更美好的自己。

【 tulaoshi.com - 编程语言 】

先简单说下前三种方式:

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 ListInterfaceConfigItem interfaceConfigList;
     public ListFtpConfigItem ftpConfigList;
     public ListAdapterConfigItem adapterConfigList;
     public void startDocument() throws SAXException {
         sysConfig = new SysConfigItem();
         interfaceConfigList = new ArrayListInterfaceConfigItem();
         ftpConfigList = new ArrayListFtpConfigItem();
         adapterConfigList = new ArrayListAdapterConfigItem();
     }
     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
  Version0100/Version
  TestFlag0/TestFlag
  BIPType
      BIPCodeBIP2B518/BIPCode
      ActivityCodeT2101518/ActivityCode
      ActionCode0/ActionCode
  /BIPType
  RoutingInfo
      OrigDomainBOSS/OrigDomain
      RouteTyperouteType/RouteType
      Routing
          HomeDomainXXXX/HomeDomain
          RouteValuerouteValue/RouteValue
      /Routing
  /RoutingInfo
  TransInfo
      SessionID2013041017222313925676/SessionID
      TransIDO2013041017222313925676/TransIDO
      TransIDOTime20130410172223/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
      RspTyperspType/RspType
      RspCoderspCode/RspCode
      RspDescrspDesc/RspDesc
  /Response
  SvcCont![CDATA[?xml version="1.0" encoding="UTF-8" standalone="yes"?
batchSyncOrderRelationReq
  msgTransactionID210001BIP2B518130410172223651627/msgTransactionID
  reqNum2/reqNum
  reqBody
      oprNumb210001BIP2B518130410172224341871/oprNumb
      subscriptionInfo
          oprTimeoprTime1/oprTime
          actionIDactionId1/actionID
          brandbrand1/brand
          effTimeeffTime1/effTime
          expireTimeexpireTime1/expireTime
          feeUser_IDfeeUserId1/feeUser_ID
          destUser_IDdestUserId1/destUser_ID
          actionReasonIDactionId1/actionReasonID
          servTypeservType1/servType
          subServTypesubServType1/subServType
          SPIDspId1/SPID
          SPServIDspServId1/SPServID
          accessModeaccessMode1/accessMode
          servParamInfo
              para_num0/para_num
              para_info
                  para_name/para_name
                  para_value/para_value
              /para_info
          /servParamInfo
          feeTypefeeType1/feeType
      /subscriptionInfo
  /reqBody
  reqBody
      oprNumb210001BIP2B518130410172224420909/oprNumb
      subscriptionInfo
          oprTimeoprTime2/oprTime
          actionIDactionId2/actionID
          brandbrand2/brand
          effTimeeffTime2/effTime
          expireTimeexpireTime2/expireTime
          feeUser_IDfeeUserId2/feeUser_ID
          destUser_IDdestUserId2/destUser_ID
          actionReasonIDactionId2/actionReasonID
          servTypeservType2/servType
          subServTypesubServType2/subServType
          SPIDspId2/SPID
          SPServIDspServId2/SPServID
          accessModeaccessMode2/accessMode
          servParamInfo
              para_num0/para_num
              para_info
                  para_name/para_name
                  para_value/para_value
              /para_info
          /servParamInfo
          feeTypefeeType2/feeType
      /subscriptionInfo
  /reqBody
/batchSyncOrderRelationReq]]/SvcCont
/InterBOSS

解码代码如下:
代码如下:

 @XmlRootElement(name = "batchSyncOrderRelationReq")

(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/bianchengyuyan/)

 @XmlAccessorType(XmlAccessType.FIELD)
 public class BatchSyncOrderRelationReq extends BossMessageBatchSyncOrderRelationReq {
     @XmlElement(name = "msgTransactionID")
     private String msgTransactionId = "";
     @XmlElement(name = "reqNum")
     private String reqNum = "";
    @XmlElement(name = "reqBody")
    private ListBatchSyncOrderRelationReqBody 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 ListBatchSyncOrderRelationReqBody getReqBodyList() {
        return this.reqBodyList;
    }
    public void setReqBodyList(ListBatchSyncOrderRelationReqBody 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;
  }
}

(本文来源于图老师网站,更多请访问http://www.tulaoshi.com/bianchengyuyan/)

来源:http://www.tulaoshi.com/n/20160219/1595035.html

延伸阅读
标签: Web开发
互联网上不计其数的信息本质上都是一个一个的HTML文档组成的,通过链接将它们串联起整个互联网。这就犹如骨肉之于人体一样,只有通过经脉才能将它们串联起来,组成一个完整的人体。 看似最基本的一个a /标签,却是HTML文档中至关重要不可或缺的一个标签。这个a /标签是页面之间链接的一个纽带,起着一个桥梁的作用。这座桥梁在页面里的也以各种...
Java中的List是可以包含重复元素的(hash code 和equals),那么对List进行去重操作有两种方式实现: 方案一:可以通过HashSet来实现,代码如下: 代码如下: class Student { private String id; private String name; public Student(String id, String name) { super(); this.id = id; this.name = name; } @Override public Stri...
Java本地接口(Java Native Interface (JNI))允许运行在Java虚拟机(Java Virtual Machine (JVM))上的代码调用本地程序和类库,或者被它们调用,这些程序和类库可以是其它语言编写的,比如C、C++或者汇编语言。 当一个程序无法完全使用Java编写时,开发者可以通过JNI来编写本地方法,比如标准Java类库并不支持的依赖于平台的特色或者程...
标签: Web开发
       对结点的属性赋值   一旦创建了结点,还要对其属性赋值,如独立的标识符,或者特性值。你要用到SetAttribute方法。该方法接收两个参数— 属性名和属性值。例如,下列代码创建了属性名SHIPPING_DATASOURCE 和属性值NORTH_ATLANTIC_SHIPPING:      objXMLroot.SetAttribute...
标签: 分娩方式
自然分娩有何优缺点 正常情况下,自然分娩是最好的分娩方式。但是自然分娩并非人人适用,也并非毫无缺点。 自然分娩是指在有安全保障的前提下,通常不加以人工干预手段,让胎儿经阴道娩出的分娩方式。孕妇在决定自然分娩时,应先了解何时预产及生产的全过程。 自然分娩适合人群: 1、年龄介于24~35岁间 2、对自然分娩有信心 3、不具备...

经验教程

90

收藏

52
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部