Java中对XML的解析详解
先简单说下前三种方式:
不过SAX方式之前也用过,本文主要介绍JAXB,这里只贴下主要代码:
importjava.util.ArrayList;
importjava.util.List;
importorg.xml.sax.Attributes;
importorg.xml.sax.SAXException;
importorg.xml.sax.helpers.DefaultHandler;
publicclassConfigParserextendsDefaultHandler{
privateStringcurrentConfigSection;
publicSysConfigItemsysConfig;
publicList<InterfaceConfigItem>interfaceConfigList;
publicList<FtpConfigItem>ftpConfigList;
publicList<AdapterConfigItem>adapterConfigList;
publicvoidstartDocument()throwsSAXException{
sysConfig=newSysConfigItem();
interfaceConfigList=newArrayList<InterfaceConfigItem>();
ftpConfigList=newArrayList<FtpConfigItem>();
adapterConfigList=newArrayList<AdapterConfigItem>();
}
publicvoidendDocument()throwsSAXException{
}
publicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesattributes)throwsSAXException{
if(qName.equalsIgnoreCase("Item")&&attributes.getLength()>0){
if(currentConfigSection.equalsIgnoreCase("SysConfigItem")){
sysConfig=newSysConfigItem(attributes);
}elseif(currentConfigSection.equalsIgnoreCase("InterfaceConfigItems")){
interfaceConfigList.add(newInterfaceConfigItem(attributes));
}elseif(currentConfigSection.equalsIgnoreCase("FtpConfigItems")){
ftpConfigList.add(newFtpConfigItem(attributes));
}elseif(currentConfigSection.equalsIgnoreCase("AdapterConfigItems")){
adapterConfigList.add(newAdapterConfigItem(attributes));
}
}else{
currentConfigSection=qName;
}
}
publicvoidendElement(Stringuri,StringlocalName,StringqName)throwsSAXException{
}
publicvoidcharacters(charch[],intstart,intlength)throwsSAXException{
}
}
importjava.lang.reflect.Field;
importjava.text.DateFormat;
importjava.text.ParseException;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importorg.xml.sax.Attributes;
publicclassConfigItemBase{
privatestaticDateFormatdateFormat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
publicConfigItemBase(){
}
/**
*目前只支持几种常用类型如果需要支持其他类型,请修改这里的代码
*
*@paramattributes
*/
publicConfigItemBase(Attributesattributes){
Class<?>cls=this.getClass();
Field[]fields=cls.getDeclaredFields();
for(Fieldfield:fields){
StringfieldType=field.getType().getSimpleName();
for(inti=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)));
}elseif(fieldType.equalsIgnoreCase("Integer")){
field.set(this,Integer.valueOf(attributes.getValue(attributes.getQName(i))));
}elseif(fieldType.equalsIgnoreCase("Double")){
field.set(this,Double.valueOf(attributes.getValue(attributes.getQName(i))));
}elseif(fieldType.equalsIgnoreCase("Date")){
field.set(this,GetDate(attributes.getValue(attributes.getQName(i))));
}else{
System.out.println("Warning:UnhandlerField("+field.getName()+"-"+fieldType+")");
}
}catch(IllegalArgumentExceptione){
e.printStackTrace();
}catch(IllegalAccessExceptione){
e.printStackTrace();
}
break;
}
}
}
}
publicStringtoString(){
Stringresult="";
Class<?>cls=this.getClass();
StringclassNameString=cls.getName();
result+=classNameString.substring(classNameString.lastIndexOf(".")+1,classNameString.length())+":";
Field[]fields=cls.getDeclaredFields();
for(Fieldfield:fields){
try{
result+=field.getName()+"="+field.get(this)+";";
}catch(IllegalArgumentExceptione){
e.printStackTrace();
}catch(IllegalAccessExceptione){
e.printStackTrace();
}
}
returnresult;
}
/**
*处理时间类型属性(时间格式要求为:yyyy-MM-ddhh:mm:ss)
*
*@paramdateString
*@return
*/
privatestaticDateGetDate(StringdateString){
Datedate=null;
try{
date=dateFormat.parse(dateString);
}catch(ParseExceptione){
e.printStackTrace();
}
returndate;
}
}
这里用比较复杂的移动BatchSyncOrderRelationReq接口XML做为示例(感觉能解这个大家基本上够用了),报文格式如下(SvcCont里的CDATA内容是报文体,太恶心了):
<?xmlversion="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[<?xmlversion="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)
publicclassBatchSyncOrderRelationReqextendsBossMessage<BatchSyncOrderRelationReq>{
@XmlElement(name="msgTransactionID")
privateStringmsgTransactionId="";
@XmlElement(name="reqNum")
privateStringreqNum="";
@XmlElement(name="reqBody")
privateList<BatchSyncOrderRelationReqBody>reqBodyList;
publicBatchSyncOrderRelationReq(){
}
publicStringgetMsgTransactionId(){
returnthis.msgTransactionId;
}
publicvoidsetMsgTransactionId(StringmsgTransactionId){
this.msgTransactionId=msgTransactionId;
}
publicStringgetReqNum(){
returnthis.reqNum;
}
publicvoidsetReqNum(StringreqNum){
this.reqNum=reqNum;
}
publicList<BatchSyncOrderRelationReqBody>getReqBodyList(){
returnthis.reqBodyList;
}
publicvoidsetReqBodyList(List<BatchSyncOrderRelationReqBody>reqBodyList){
this.reqBodyList=reqBodyList;
}
@Override
publicBatchSyncOrderRelationReqDeserialized(StringinterBossXmlContent)throwsBusinessException{
try{
//deserializedforhead
JAXBContextjaxbCxt4Head=JAXBContext.newInstance(MessageHead.class);
Unmarshallerunmarshaller4Head=jaxbCxt4Head.createUnmarshaller();
MessageHeadhead=(MessageHead)unmarshaller4Head.unmarshal(newStringReader(interBossXmlContent));
//deserializedforSyncOrderRelationReqbody
JAXBContextjaxbCxt4Body=JAXBContext.newInstance(BatchSyncOrderRelationReq.class);
Unmarshallerunmarshaller4Body=jaxbCxt4Body.createUnmarshaller();
BatchSyncOrderRelationReqbatchSyncOrderRelationReq=(BatchSyncOrderRelationReq)unmarshaller4Body.unmarshal(newStringReader(head.getSvcCont().trim()));
batchSyncOrderRelationReq.setHead(head);
returnbatchSyncOrderRelationReq;
}catch(JAXBExceptione){
thrownewBusinessException("SyncOrderRelationReq.Deserialized()Error!("+interBossXmlContent+")",e);
}
}
}
@XmlAccessorType(XmlAccessType.FIELD)
publicclassBatchSyncOrderRelationReqBody{
@XmlElement(name="oprNumb")
privateStringoprNumb="";
@XmlElement(name="subscriptionInfo")
privateSubscriptionInfosubscriptionInfo;
publicBatchSyncOrderRelationReqBody(){
}
publicBatchSyncOrderRelationReqBody(StringoprNumb,SubscriptionInfosubscriptionInfo){
this.oprNumb=oprNumb;
this.subscriptionInfo=subscriptionInfo;
}
publicStringgetOprNumb(){
returnthis.oprNumb;
}
publicvoidsetOprNumb(StringoprNumb){
this.oprNumb=oprNumb;
}
publicSubscriptionInfogetSubscriptionInfo(){
returnthis.subscriptionInfo;
}
publicvoidsetSubscriptionInfo(SubscriptionInfosubscriptionInfo){
this.subscriptionInfo=subscriptionInfo;
}
}
@XmlAccessorType(XmlAccessType.FIELD)
publicclassSubscriptionInfo{
@XmlElement(name="oprTime")
privateStringoprTime="";
@XmlElement(name="actionID")
privateStringactionId="";
@XmlElement(name="brand")
privateStringbrand="";
@XmlElement(name="effTime")
privateStringeffTime="";
@XmlElement(name="expireTime")
privateStringexpireTime="";
@XmlElement(name="feeUser_ID")
privateStringfeeUserId="";
@XmlElement(name="destUser_ID")
privateStringdestUserId="";
@XmlElement(name="actionReasonID")
privateStringactionReasonId="";
@XmlElement(name="servType")
privateStringservType="";
@XmlElement(name="subServType")
privateStringsubServType="";
@XmlElement(name="SPID")
privateStringspId="";
@XmlElement(name="SPServID")
privateStringspServId="";
@XmlElement(name="accessMode")
privateStringaccessMode="";
@XmlElement(name="feeType")
privateStringfeeType="";
publicSubscriptionInfo(){
}
publicSubscriptionInfo(
StringoprTime,
StringactionId,
Stringbrand,
StringeffTime,
StringexpireTime,
StringfeeUserId,
StringdestUserId,
StringactionReasonId,
StringservType,
StringsubServType,
StringspId,
StringspServId,
StringaccessMode,
StringfeeType){
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;
}
publicStringgetOprTime(){
returnthis.oprTime;
}
publicvoidsetOprTime(StringoprTime){
this.oprTime=oprTime;
}
publicStringgetActionId(){
returnthis.actionId;
}
publicvoidsetActionId(StringactionId){
this.actionId=actionId;
}
publicStringgetBrand(){
returnthis.brand;
}
publicvoidsetBrand(Stringbrand){
this.brand=brand;
}
publicStringgetEffTime(){
returnthis.effTime;
}
publicvoidsetEffTime(StringeffTime){
this.effTime=effTime;
}
publicStringgetExpireTime(){
returnthis.expireTime;
}
publicvoidsetExpireTime(StringexpireTime){
this.expireTime=expireTime;
}
publicStringgetFeeUserId(){
returnthis.feeUserId;
}
publicvoidsetFeeUserId(StringfeeUserId){
this.feeUserId=feeUserId;
}
publicStringgetDestUserId(){
returnthis.destUserId;
}
publicvoidsetDestUserId(StringdestUserId){
this.destUserId=destUserId;
}
publicStringgetActionReasonId(){
returnthis.actionReasonId;
}
publicvoidsetActionReasonId(StringactionReasonId){
this.actionReasonId=actionReasonId;
}
publicStringgetServType(){
returnthis.servType;
}
publicvoidsetServType(StringservType){
this.servType=servType;
}
publicStringgetSubServType(){
returnthis.subServType;
}
publicvoidsetSubServType(StringsubServType){
this.subServType=subServType;
}
publicStringgetSpId(){
returnthis.spId;
}
publicvoidsetSpId(StringspId){
this.spId=spId;
}
publicStringgetSpServId(){
returnthis.spServId;
}
publicvoidsetSpServId(StringspServId){
this.spServId=spServId;
}
publicStringgetAccessMode(){
returnthis.accessMode;
}
publicvoidsetAccessMode(StringaccessMode){
this.accessMode=accessMode;
}
publicStringgetFeeType(){
returnthis.feeType;
}
publicvoidsetFeeType(StringfeeType){
this.feeType=feeType;
}
}
相关文章
- java random函数用法_JAVA的Random类的用法详解[通俗易懂]
- java xml解析框架_JAVA解析xml的五种方式对比
- java输出值取后两位小数,Java输出结果保留两位小数
- java常量有哪些_JAVA常量介绍「建议收藏」
- 在线学习Java的几个网站,别再盲目学习java了![通俗易懂]
- MySQL字段类型如何转为java_Java JDBC中,MySQL字段类型到JAVA类型的转换
- java平均的随机数_Java 随机数详解「建议收藏」
- 【JAVA面试必会】JMM高并发详解(java内存模型、JMM三大特征、volatile关键字 )「建议收藏」
- java 异或加密_Java异或技操作给任意的文件加密原理及使用详解
- Java servlet中web xml文件内容执行原理
- java JNI: C 语言调用 Java 方法示例详解编程语言
- java通过XPath解析xml节点详解编程语言
- java使用SAX解析xml详解编程语言
- 使用DOMParser 解析xml的Java代码详解编程语言
- 把Java生成的RSA公钥、私钥转换成.NET使用的XML格式详解编程语言
- Java连接MySQL数据库的简单步骤(java如何连接mysql数据库)
- Java数据持久层框架 MyBatis之API学习三(XML 映射配置文件)详解编程语言
- Importing XML files into MySQL: The Complete Guide for Data Integration(xml文件导入mysql)
- Linux轻松打开XML文件(linux打开xml文件)
- 异常Java程序捕获Oracle异常从失败中学习(java捕获oracle)
- 使用MySQL实现XML数据导入(mysql xml 导入)
- 编程Oracle数据库中实现Java编程的突破之道(oracle使用java)
- java操作(DOM、SAX、JDOM、DOM4J)xml方式的四种比较与详解
- Java程序员的10道常见的XML面试问答题(XML术语详解)