Java中对XML的解析详解_java

先简单说下前三种方式:

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;
    }
}

时间: 2024-10-16 04:41:51

Java中对XML的解析详解_java的相关文章

多用多学之Java中的Set,List,Map详解_java

很长时间以来一直代码中用的比较多的数据列表主要是List,而且都是ArrayList,感觉有这个玩意就够了.ArrayList是用于实现动态数组的包装工具类,这样写代码的时候就可以拉进拉出,迭代遍历,蛮方便的. 也不知道从什么时候开始慢慢的代码中就经常会出现HashMap和HashSet之类的工具类.应该说HashMap比较多一些,而且还是面试经典题,平时也会多看看.开始用的时候简单理解就是个键值对应表,使用键来找数据比较方便.随后深入了解后发现 这玩意还有点小奥秘,特别是新版本的JDK对Has

关于java中构造函数的一些知识详解_java

java的构造函数是一个非常重要的作用,首先java里的构造函数是可以重载的,而且因为也是可以继承在父类的构造函数,所以在子类里,首先必然是调用父类的构造函数.可以看下面的两个例子来对比: public class Test { public static void main(String args[]) { B b = new B(100); } } class A { public A() { System.out.println("A without any parameter"

Java 中的字符串常量池详解_java

Java中的字符串常量池 Java中字符串对象创建有两种形式,一种为字面量形式,如String str = "droid";,另一种就是使用new这种标准的构造对象的方法,如String str = new String("droid");,这两种方式我们在代码编写时都经常使用,尤其是字面量的方式.然而这两种实现其实存在着一些性能和内存占用的差别.这一切都是源于JVM为了减少字符串对象的重复创建,其维护了一个特殊的内存,这段内存被成为字符串常量池或者字符串字面量池.

java中set接口使用方法详解_java

java中的set接口有如下的特点: 不允许出现重复元素: 集合中的元素位置无顺序: 有且只有一个值为null的元素. 因为java中的set接口模仿了数学上的set抽象,所以,对应的数学上set的特性为: 互异性:一个集合中,任何两个元素都认为是不相同的,即每个元素只能出现一次.无序性:一个集合中,每个元素的地位都是相同的,元素之间是无序的.集合上可以定义序关系,定义了序关系后,元素之间就可以按照序关系排序.但就集合本身的特性而言,元素之间没有必然的序.空集的性质:空集是一切集合的子集    

java中queue接口的使用详解_java

Queue接口与List.Set同一级别,都是继承了Collection接口.LinkedList实现了Queue接口.Queue接口窄化了对LinkedList的方法的访问权限(即在方法中的参数类型如果是Queue时,就完全只能访问Queue接口所定义的方法 了,而不能直接访问 LinkedList的非Queue的方法),以使得只有恰当的方法才可以使用.BlockingQueue 继承了Queue接口.  队列是一种数据结构.它有两个基本操作:在队列尾部加人一个元素,和从队列头部移除一个元素就

Java中的迭代和递归详解_java

前言 最近在看书的时候看到这一内容,感觉还是蛮有收获的.迭代使用的是循环(for,while,do...wile)或者迭代器,当循环条件不满足时退出.而递归,一般是函数递归,可以是自身调用自身,也可以是非直接调用,即方法A调用方法B,而方法B反过来调用方法A,递归退出的条件为if,else语句,当条件符合基的时候退出. 上面是迭代和递归的语法特性,他们在Java中有什么不同呢?下面通过这篇文章来详细了解了解. 一.递归 提到迭代,不得不提一个数学表达式: n!=n*(n-1)*(n-2)*...

Java中对象序列化与反序列化详解_java

本文实例讲述了Java中对象序列化与反序列化.分享给大家供大家参考.具体如下: 一.简介 对象序列化(Serializable)是指将对象转换为字节序列的过程,而反序列化则是根据字节序列恢复对象的过程. 序列化一般用于以下场景: 1.永久性保存对象,保存对象的字节序列到本地文件中: 2.通过序列化对象在网络中传递对象: 3.通过序列化在进程间传递对象. 对象所属的类必须实现Serializable或是Externalizable接口才能被序列化.对实现了Serializable接口的类,其序列化

java中List集合及其遍历详解_java

1. 首先List<E>集合继承与Collection<E>,是一个接口.    ①  Collection (集合框架是JDK1.2版本出现的)    ②   list:是有序的,元素可以重复,以为该集合体系有索引.      经常用到的是实现该接口的ArrayList和LinkedList类    ③   Arraylist:  底层的数据结构使用的是数组结构,   特点: 查询速度很快,但是增删稍慢.线程不同步          LinkedList: 底层使用的是链表数据结

浅谈java中静态方法的重写问题详解_java

首先来看看以下程序将会打印出什么: 复制代码 代码如下: class Dog {    public static void bark() {        System.out.print("woof ");    }} class Basenji extends Dog {    public static void bark() { }} public class Bark {    public static void main(String args[]) {