In Java 3, the XML parsing DOM method, the SAX method, and The StAX Method

Source: Internet
Author: User
Tags dateformat

Let's briefly describe the first three methods:

DOM Mode: I personally understand XmlDocument similar to. net. It is inefficient at parsing, occupies memory, and is not suitable for parsing large XML files;
SAX Mode: 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 method 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:

Copy codeThe Code is as follows: 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. inclusignorecase ("Item") & attributes. getLength ()> 0 ){
If (currentConfigSection. inclusignorecase ("SysConfigItem ")){
SysConfig = new SysConfigItem (attributes );
} Else if (currentConfigSection. inclusignorecase ("InterfaceConfigItems ")){
InterfaceConfigList. add (new InterfaceConfigItem (attributes ));
} Else if (currentConfigSection. inclusignorecase ("FtpConfigItems ")){
FtpConfigList. add (new FtpConfigItem (attributes ));
} Else if (currentConfigSection. inclusignorecase ("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 {
}
}

Copy codeThe Code is as follows: 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 several common types are supported. To support other types, modify the code here.
*
* @ 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). inclusignorecase (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;
}
/**
* Processing time type attributes (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 ):

Copy codeThe Code is as follows: <? 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> 210001bip2b518130417172223651627 </msgTransactionID>
<ReqNum> 2 </reqNum>
<ReqBody>
<OprNumb> 210001bip2b518130109172224341871 </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> 210001bip2b518130109172224420909 </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>

The decoding code is as follows:Copy codeThe Code is as follows: @ 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)Copy codeThe Code is as follows: 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)Copy codeThe Code is as follows: 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;
}
}

Related Article

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.