解析xml(當節點中有多個子節點)


概要:解析一個xml,當一個節點中又包含多個子節點如何解析,對比一個節點中不包括其他節點的情況。

一,xml樣例

<cisReports batNo="查詢批次號" unitName="查詢單位名稱" subOrgan="分支機構名稱" queryUserID="查詢操作員登錄名" queryCount="查詢請求數量" receiveTime="查詢申請時間,格式YYYYMMDD HH24:mm:ss">
    <!-- 以下為每個報告申請查得情況 1..n -->
    <cisReport reportID="報告ID" buildEndTime="報告生成結束時間,格式YYYY-MM-DD HH24:mm:ss" queryReasonID="查詢原因ID,詳見數據字典" subReportTypes="查詢的收費子報告ID,多個收費子報告ID用逗號分隔" treatResult="對應的收費子報告收費次數,與subReportTypes一一對應,為大於等於0的值的集合,用逗號分隔" subReportTypesShortCaption="報告查詢類型" refID="引用ID,為查詢申請條件中的引用ID" hasSystemError="有否系統錯誤,true:有錯誤,false:無錯誤" isFrozen="該客戶是否被凍結,true:被凍結,false:未被凍結">
              <!--  個人基本信息 0..1 -->
        <personBaseInfo subReportType="子報告ID" subReportTypeCost="收費子報告ID" treatResult="子報告查詢狀態,1:查得,2:未查得,3:其他原因未查得" treatErrorCode="treatResult=3時的錯誤代碼,詳見數據字典,treatResult!=3時,該屬性不存在" errorMessage="treatResult=3時的錯誤描述信息,treatResult!=3時,該屬性的值為空">
            <!-- 內容節點,0..1  -->
            <item>
                <!--  最新基本信息 1..1 -->
          //lastBaseInfo節點中不包含其他節點 <lastBaseInfo> <name>規范化后的姓名</name> <gender>性別代碼:1 男 2女 3 不詳</gender> <birthday>出生日期,格式YYYYMMDD</birthday> <marriageStatus>婚姻狀況ID</marriageStatus> <registerAddress>規范化的戶籍地址</registerAddress> <currentAddress>規范化的現住址</currentAddress> <tel>聯系電話</tel> <mobile>移動電話</mobile> <occupationType>職業ID</occupationType> <positionType>職務ID</positionType> <titleType>職稱ID</titleType> <education>教育程度id</education> <infoDate>信息獲取日期,格式YYYYMMDD,可能為空。</infoDate> </lastBaseInfo> <!-- 身份警示信息 1..1 -->
          //documentAlert節點中又包含多個item子節點 <documentAlert> <!-- 0..n -->//代表可能包含多個item節點 <item> <name>規范化后的姓名</name> <documentNo>規范化后的證件號碼</documentNo> <documentType>證件類型ID,詳見數據字典</documentType> <country>證件簽發地三位英文國際編碼,詳見數據字典</country> <gender>性別ID,1:男,2:女,3:不詳</gender> <birthday>出生日期,格式YYYYMMDD</birthday> <infoDate>信息獲取日期,格式YYYYMMDD,可能為空。</infoDate> </item> </documentAlert> </item> </personBaseInfo>

二,代碼

/**
     * @return com.pingan.credit.model.py.ShenZhenPersonalCredit.PersonBaseInfo
     * @Description: 2. 解析 個人基本信息
     * @date 2017/10/9 17:11
     */
    private PersonBaseInfo getPersonBaseInfoNode(Element cisReport) throws Exception {
        // 獲取節點屬性
        Element personBaseInfoElement = cisReport.element("personBaseInfo");
        PersonBaseInfo personBaseInfo = null;
        if (personBaseInfoElement != null) {
            List<Attribute> personBaseInfoList = personBaseInfoElement.attributes();

            Map<String, String> attributeMap = personBaseInfoList.stream()
                    .collect(Collectors.toMap(Attribute::getName, Attribute::getValue));
            personBaseInfo = (PersonBaseInfo) CommonUtils.setValueOfSuperClass(PersonBaseInfo.class, attributeMap);

            //treatResult=1 表示查詢狀態 查得
            if (SUCCESS.equals(attributeMap.get(TREAT_RESULT))) {
                Element item = personBaseInfoElement.element("item");
                if (item != null) {
                    //2 最新基本信息
            //解析單個節點,不包含子節點 Element lastBaseElement = item.element("lastBaseInfo"); if (lastBaseElement != null) { List<Element> lastBaseInfoList = item.element("lastBaseInfo").elements(); Map<String, String> lastBaseInfoListResultMap = XmlUtil.getResultMap(lastBaseInfoList); LastBaseInfo lastBaseInfo = new LastBaseInfo(); personBaseInfo.setLastBaseInfo((LastBaseInfo) CommonUtils.setValue(lastBaseInfo, lastBaseInfoListResultMap)); } //6 身份警示信息
            //節點中包含多個子節點 Element documentAlertElement = item.element("documentAlert"); if (documentAlertElement != null) { List<Element> documentAlertList = item.element("documentAlert").elements(); if (!ListUtil.isEmpty(documentAlertList)) { List<DocumentAlert> itemList = new ArrayList<>();
                 //遍歷子節點,獲取每個子節點中節點內容
for (Element e : documentAlertList) { DocumentAlert documentAlert = new DocumentAlert(); documentAlert = (DocumentAlert) CommonUtils.setValue(documentAlert, XmlUtil.getResultMap(e.elements())); itemList.add(documentAlert); } personBaseInfo.setDocumentAlerts(itemList); } } } } } return personBaseInfo; }

解析節點反射賦值

    /**
     * 將元素節點轉換成map
     */
    public static Map<String, String> getResultMap(List<Element> items) {
        Map<String, String> map = new HashMap<>(32);
        for (Element e : items) {
            if (StringUtils.isNotEmpty(e.getData().toString())) {
                map.put(e.getName(), e.getData().toString());
            }
        }
        return map;
    }
    /**
     * @param object, resultMap
     * @return java.lang.Object
     * @Description: 通過反射為實體類賦值
     * @date 2017/8/30 9:43
     */
    public static Object setValue(Object object, Map<String, String> resultMap) throws Exception {
        try {
            Class<?> obj = object.getClass();
            Field[] fields = obj.getDeclaredFields();
            setValue(object, resultMap, fields);

            return object;
        } catch (IllegalAccessException e) {
            logger.info("IllegalAccessException@CommonUtils:" + e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.info("Exception@CommonUtils:" + e.getMessage());
            throw e;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM