热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Java中对XML的解析详解

目前我知道的JAVA解析XML的方式有:DOM,SAX,StAX;如果选用这几种,感觉还是有点麻烦;如果使用:JAXB(JavaArchitectureforXMLBinding),个人觉得太方便了

先简单说下前三种方式:

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 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() {

    }

    /**
     * 目前只支持几种常用类型 如果需要支持其他类型,请修改这里的代码
     *
     * @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                 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内容是报文体,太恶心了):
代码如下:



    0100
    0
   
        BIP2B518
        T2101518
        0
   

   
        BOSS
        routeType
       
            XXXX
            routeValue
       

   

   
        2013041017222313925676
        2013041017222313925676
        20130410172223
       
       
   

   
       
       
       
       
       
       
       
       
       
       
       
   

   
        rspType
        rspCode
        rspDesc
   

   

    210001BIP2B518130410172223651627
    2
   
        210001BIP2B518130410172224341871
       
            oprTime1
            actionId1
            brand1
            effTime1
            expireTime1
            feeUserId1
            destUserId1
            actionId1
            servType1
            subServType1
            spId1
            spServId1
            accessMode1
           
                0
               
                   
                   
               

           

            feeType1
       

   

   
        210001BIP2B518130410172224420909
       
            oprTime2
            actionId2
            brand2
            effTime2
            expireTime2
            feeUserId2
            destUserId2
            actionId2
            servType2
            subServType2
            spId2
            spServId2
            accessMode2
           
                0
               
                   
                   
               

           

            feeType2
       

   

]]>



解码代码如下:
代码如下:

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


推荐阅读
  • YOLOv7基于自己的数据集从零构建模型完整训练、推理计算超详细教程
    本文介绍了关于人工智能、神经网络和深度学习的知识点,并提供了YOLOv7基于自己的数据集从零构建模型完整训练、推理计算的详细教程。文章还提到了郑州最低生活保障的话题。对于从事目标检测任务的人来说,YOLO是一个熟悉的模型。文章还提到了yolov4和yolov6的相关内容,以及选择模型的优化思路。 ... [详细]
  • 本文介绍了设计师伊振华受邀参与沈阳市智慧城市运行管理中心项目的整体设计,并以数字赋能和创新驱动高质量发展的理念,建设了集成、智慧、高效的一体化城市综合管理平台,促进了城市的数字化转型。该中心被称为当代城市的智能心脏,为沈阳市的智慧城市建设做出了重要贡献。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • 学习笔记(34):第三阶段4.2.6:SpringCloud Config配置中心的应用与原理第三阶段4.2.6SpringCloud Config配置中心的应用与原理
    立即学习:https:edu.csdn.netcourseplay29983432482?utm_sourceblogtoedu配置中心得核心逻辑springcloudconfi ... [详细]
  • 目录实现效果:实现环境实现方法一:基本思路主要代码JavaScript代码总结方法二主要代码总结方法三基本思路主要代码JavaScriptHTML总结实 ... [详细]
  • Android中高级面试必知必会,积累总结
    本文介绍了Android中高级面试的必知必会内容,并总结了相关经验。文章指出,如今的Android市场对开发人员的要求更高,需要更专业的人才。同时,文章还给出了针对Android岗位的职责和要求,并提供了简历突出的建议。 ... [详细]
  • Centos7.6安装Gitlab教程及注意事项
    本文介绍了在Centos7.6系统下安装Gitlab的详细教程,并提供了一些注意事项。教程包括查看系统版本、安装必要的软件包、配置防火墙等步骤。同时,还强调了使用阿里云服务器时的特殊配置需求,以及建议至少4GB的可用RAM来运行GitLab。 ... [详细]
  • [译]技术公司十年经验的职场生涯回顾
    本文是一位在技术公司工作十年的职场人士对自己职业生涯的总结回顾。她的职业规划与众不同,令人深思又有趣。其中涉及到的内容有机器学习、创新创业以及引用了女性主义者在TED演讲中的部分讲义。文章表达了对职业生涯的愿望和希望,认为人类有能力不断改善自己。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 20211101CleverTap参与度和分析工具功能平台学习/实践
    1.应用场景主要用于学习CleverTap的使用,该平台主要用于客户保留与参与平台.为客户提供价值.这里接触到的原因,是目前公司用到该平台的服务~2.学习操作 ... [详细]
  • 如何用UE4制作2D游戏文档——计算篇
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了如何用UE4制作2D游戏文档——计算篇相关的知识,希望对你有一定的参考价值。 ... [详细]
  • 安卓select模态框样式改变_微软Office风格的多端(Web、安卓、iOS)组件库——Fabric UI...
    介绍FabricUI是微软开源的一套Office风格的多端组件库,共有三套针对性的组件,分别适用于web、android以及iOS,Fab ... [详细]
  • 使用在线工具jsonschema2pojo根据json生成java对象
    本文介绍了使用在线工具jsonschema2pojo根据json生成java对象的方法。通过该工具,用户只需将json字符串复制到输入框中,即可自动将其转换成java对象。该工具还能解析列表式的json数据,并将嵌套在内层的对象也解析出来。本文以请求github的api为例,展示了使用该工具的步骤和效果。 ... [详细]
  • 关于我们EMQ是一家全球领先的开源物联网基础设施软件供应商,服务新产业周期的IoT&5G、边缘计算与云计算市场,交付全球领先的开源物联网消息服务器和流处理数据 ... [详细]
  • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
    原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
author-avatar
婕小米
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有