Java中对XML的解析详解

先简单说下前三种方式:

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解析XML几种方式小结

    java解析XML几种方式小结 第一种:DOM. DOM的全称是Document Object Model,也即文档对象模型.在应用程序中,基于DOM的XML分析器将一个XML文档转换成一个对象模型的集合(通常称DOM树),应用程序正是通过对这个对象模型的操作,来实现对XML文档数据的操作.通过DOM接口,应用程序可以在任何时候访问XML文档中的任何一部分数据,因此,这种利用DOM接口的机制也被称作随机访问机制. DOM接口提供了一种通过分层对象模型来访问XML文档信息的方式,这些分层对象模型依

  • java解析xml常用的几种方式总结

    各种方法都用过.现在总结一下. 经常记不住,要找资料.现在总结一下. xml 文件如下: 复制代码 代码如下: <?xml version="1.0" encoding="ISO-8859-1"?><bookstore><book category="COOKING">  <title lang="en">Everyday Italian</title>  <a

  • java使用xpath和dom4j解析xml

    1 XML文件解析的4种方法 通常解析XML文件有四种经典的方法.基本的解析方式有两种,一种叫SAX,另一种叫DOM.SAX是基于事件流的解析,DOM是基于XML文档树结构的解析.在此基础上,为了减少DOM.SAX的编码量,出现了JDOM,其优点是,20-80原则(帕累托法则),极大减少了代码量.通常情况下JDOM使用时满足要实现的功能简单,如解析.创建等要求.但在底层,JDOM还是使用SAX(最常用).DOM.Xanan文档.另外一种是DOM4J,是一个非常非常优秀的Java XML API,

  • Java生成和解析XML格式文件和字符串的实例代码

    1.基础知识: Java解析XML一般有四种方法:DOM.SAX.JDOM.DOM4J. 2.使用介绍 1).DOM (1)简介 由W3C(org.w3c.dom)提供的接口,它将整个XML文档读入内存,构建一个DOM树来对各个节点(Node)进行操作.优点就是整个文档都一直在内存中,我们可以随时访问任何节点,并且对树的遍历也是比较熟悉的操作:缺点则是耗内存,并且必须等到所有的文档都读入内存才能进行处理. (2)示例代码: 复制代码 代码如下: <?xml version="1.0&quo

  • java 使用JDOM解析xml文件

    JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术对XML文档实现解析.生成.序列化以及多种操作.JDOM直接为JAVA编程服务.它利用更为强有力的JAVA语言的诸多特性(方法重载.集合概念以及映射),把SAX和DOM的功能有效地结合起来.JDOM的官方地址:http://www.jdom.org/1.首先新建一个接口和2个类,为后续做准备[Moveable.java] 复制代码 代码如下: package com.njupt.zhb.test;public interface Mov

  • 在java中使用dom4j解析xml(示例代码)

    虽然Java中已经有了Dom和Sax这两种标准解析方式 但其操作起来并不轻松,对于我这么一个初学者来说,其中部分代码是活生生的恶心 为此,伟大的第三方开发组开发出了Jdom和Dom4j等工具 鉴于目前的趋势,我们这里来讲讲Dom4j的基本用法,不涉及递归等复杂操作 Dom4j的用法很多,官网上的示例有那么点儿晦涩,这里就不写了 首先我们需要出创建一个xml文档,然后才能对其解析 xml文档: 复制代码 代码如下: <?xml version="1.0" encoding=&quo

  • java实现简单解析XML文件功能示例

    本文实例讲述了java实现简单解析XML文件功能.分享给大家供大家参考,具体如下: package demo; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException;

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

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

  • java使用xpath解析xml示例分享

    XPath即为XML路径语言(XML Path Language),它是一种用来确定XML文档中某部分位置的语言.XPath基于XML的树状结构,提供在数据结构树中找寻节点的能力.起初 XPath 的提出的初衷是将其作为一个通用的.介于XPointer与XSL间的语法模型.但是 XPath 很快的被开发者采用来当作小型查询语言. XPathTest.java 复制代码 代码如下: package com.hongyuan.test; import java.io.File;import java

  • java dom4j解析xml用到的几个方法

    1. 读取并解析XML文档: 复制代码 代码如下: SAXReader reader = new SAXReader(); Document document = reader.read(new File(fileName)); reader的read方法是重载的,可以从InputStream, File, Url等多种不同的源来读取.得到的Document对象就带表了整个XML. 读取的字符编码是按照XML文件头定义的编码来转换.如果遇到乱码问题,注意要把各处的编码名称保持一致即可. 2. 取

  • Java解析XML的四种方法详解

    XML现在已经成为一种通用的数据交换格式,它的平台无关性,语言无关性,系统无关性,给数据集成与交互带来了极大的方便.对于XML本身的语法知识与技术细节,需要阅读相关的技术文献,这里面包括的内容有DOM(Document Object Model),DTD(Document Type Definition),SAX(Simple API for XML),XSD(Xml Schema Definition),XSLT(Extensible Stylesheet Language Transform

随机推荐