dom4j解析多层xml

package com.bessky.hrmis.test;

import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Dom4JDemo {
    public static void main(String[] args) throws Exception {
        // 1.创建Reader对象
        SAXReader reader = new SAXReader();
        String str = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\r\n"
            + "    <cas:authenticationSuccess>\r\n" + "        <cas:user>hanke_tom</cas:user>\r\n"
            + "        <cas:attributes>\r\n"
            + "            <cas:credentialType>tom</cas:credentialType>\r\n"
            + "            <cas:logout_url>http://192.168.1.5:8080/sso/logout</cas:logout_url>\r\n"
            + "            <cas:isFromNewLogin>false</cas:isFromNewLogin>\r\n"
            + "            <cas:authenticationDate>2019-11-26T17:47:55.789+08:00[Asia/Shanghai]</cas:authenticationDate>\r\n"
            + "            <cas:user_id>01</cas:user_id>\r\n"
            + "            <cas:authenticationMethod>TomAuthenticationHandler</cas:authenticationMethod>\r\n"
            + "            <cas:successfulAuthenticationHandlers>TomAuthenticationHandler</cas:successfulAuthenticationHandlers>\r\n"
            + "            <cas:name>张三</cas:name>\r\n"
            + "            <cas:longTermAuthenticationRequestTokenUsed>false</cas:longTermAuthenticationRequestTokenUsed>\r\n"
            + "            <cas:job_number>00001</cas:job_number>\r\n"
            + "            <cas:username>hanke_tom</cas:username>\r\n" + "            </cas:attributes>\r\n"
            + "    </cas:authenticationSuccess>\r\n" + "</cas:serviceResponse>";
        // 2.加载xml
        Document document = DocumentHelper.parseText(str);
        // 3.获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        
        System.out.println("根节点:" + rootElement.getName()); // 拿到根节点的名称
        
        Iterator bbbb = rootElement.elementIterator("authenticationSuccess"); 
        
        while (bbbb.hasNext()) {
            Element recordEless = (Element) bbbb.next();
            Iterator cccc = recordEless.elementIterator("attributes"); 
            while (cccc.hasNext()) {
                Element itemEle = (Element) cccc.next();
                String username = itemEle.elementTextTrim("job_number"); 
                System.err.println("---------"+username);
            }
        }
    }
}

如果后面还有子级继续while向下取数据

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值