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向下取数据