Explanation of XML parsing in Java

Source: Internet
Author: User
Currently, I know that the methods for parsing XML in JAVA are DOM, SAX, and StAX. if you use these methods, it is still a little troublesome. if you use JAXB (javaubuntureforxmlbinding ), I personally think it is too convenient to briefly describe the first three methods:

DOM mode: I personally understand XmlDocument similar to. net, which is inefficient in parsing and occupies memory. it is not suitable for parsing large XML files;

SAX method: Event-Based Parsing. when a part of xml is parsed, a specific event is triggered. you can define in a custom parsing class what to do when an event is triggered; I personally feel that there is a very different way, I don't know. is there a similar way under the. Net system?

StAX mode: I personally understand the XmlReader mode similar to. net, which features high efficiency and low memory usage and is suitable for parsing large XML files;

However, we have also used the SAX method before. This article mainly introduces JAXB. here we only paste the main code:

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
 
   interfaceConfigList;     public List
  
    ftpConfigList;     public List adapterConfigList;     public void startDocument() throws SAXException {         sysConfig = new SysConfigItem();         interfaceConfigList = new ArrayList
   
    ();         ftpConfigList = new ArrayList
    
     ();         adapterConfigList = new ArrayList();     }     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 () {}/*** currently only supports several common types. to support other types, modify the code ** @ 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. repeated signorecase ("Double") {field. set (this, Double. valueOf (attributes. getValue (attributes. getQName (I);} else if (fieldType. specified signorecase ("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;}/*** processing time type attribute (the time format must be 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 ;}}

The following describes the most convenient JAXB (Java Architecture for XML Binding)
Here we use the complicated mobile BatchSyncOrderRelationReq interface XML as an example (I think this is basically enough). the Message format is as follows (the CDATA content in SvcCont is a style report, which is disgusting ):

 
     
  
   0100
      
  
   0
      
          
   
    BIP2B518
           T2101518        0    
      
          
   
    BOSS
           
   
    routeType
           
               
    
     XXXX
                
    
     routeValue
            
       
      
          
   
    2013041017222313925676
           
   
    2013041017222313925676
           
   
    20130410172223
           
           
       
      
          
           
           
           
           
           
           
           
           
           
           
       
      
          
   
    rspType
           
   
    rspCode
           
   
    rspDesc
       
      
  <?xml version="1.0" encoding="UTF-8" standalone="yes"?><batchSyncOrderRelationReq>    <msgTransactionID>210001BIP2B518130410172223651627</msgTransactionID>    <reqNum>2</reqNum>    <reqBody>        <oprNumb>210001BIP2B518130410172224341871</oprNumb>        <subscriptionInfo>            <oprTime>oprTime1</oprTime>            actionId1</actionID>            <brand>brand1</brand>            <effTime>effTime1</effTime>            <expireTime>expireTime1</expireTime>            <feeUser_ID>feeUserId1</feeUser_ID>            <destUser_ID>destUserId1</destUser_ID>            actionId1</actionReasonID>            <servType>servType1</servType>            <subServType>subServType1</subServType>            <SPID>spId1</SPID>            <SPServID>spServId1</SPServID>            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>            actionId2</actionID>            <brand>brand2</brand>            <effTime>effTime2</effTime>            <expireTime>expireTime2</expireTime>            <feeUser_ID>feeUserId2</feeUser_ID>            <destUser_ID>destUserId2</destUser_ID>            actionId2</actionReasonID>            <servType>servType2</servType>            <subServType>subServType2</subServType>            <SPID>spId2</SPID>            <SPServID>spServId2</SPServID>            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>
  
 

The decoding code is as follows:

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

For more details about XML parsing in Java, please follow the PHP Chinese network!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.