/**
* 解析xml字符串,获取各项属性内容
* readXML方法描述:
*
* @author : gc
* @createTime : 2019-4-26 下午4:37:50
*/
private static void readXML() {
//String xmlResult = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><users><user id=\"10001\"><name>张三</name><role>群主</role><sex>男</sex><content>今天天气真不错!</content><time>2016-04-25 16:43:28</time></user><user id=\"10002\"> <name>李四</name><role>管理员</role><sex>男</sex><content>http://192.168.0.190:9999/beike/data/b3217f668.png</content><time>2016-04-25 16:45:08</time></user></users>";
String xmlResult="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<dataset code=\"T_MD_HR_EMPLOYEE\" name=\"人员\" action=\"UPDATE\" msgid=\"C31ABFC900B14BDAA98B1B7B45EB5D9C\" createtime=\"2019-06-27 22:04:55\" count=\"1\">"+
"<data ids='2'><EMPLOYEE_NAME id='name'>王源</EMPLOYEE_NAME><USERNUMBER>2036000154000361</USERNUMBER>"+
"<EMPLOYEE_CODE type=\"pk\">2036000154000361</EMPLOYEE_CODE>"+
"<ORG_CODE refdesc=\"赣州卷烟厂\">1010</ORG_CODE>"+
"<DEPARTMENT_CODE refdesc=\"卷包车间\">203600015558</DEPARTMENT_CODE>"+
"<SEX>1</SEX><CRDNUM>362133197605060013</CRDNUM><REMARK/></data></dataset>";
try {
// 1.将xml格式字符串转化为DOM对象
org.dom4j.Document document = DocumentHelper.parseText(xmlResult);
// 2.获取根结点对象:dataset
Element rootElement = document.getRootElement();
// 3.获取根节点的标签属性:
// a)通过遍历方法attributeIterator()拿到所有的标签属性
for(Iterator attrIter = rootElement.attributeIterator(); attrIter.hasNext();){
Attribute attribute = (Attribute) attrIter.next();
if (null != attribute) {
String attributeVal = attribute.getValue();//拿到属性值
String attributeName = attribute.getName();//拿到属性名
System.out.println(attributeName + ": " + attributeVal);
}
}
// b)通过属性attribute("code") 拿到单个标签属性
Attribute attribute = rootElement.attribute("code");
if (null != attribute) {
String attributeVal = attribute.getValue();
String attributeName = attribute.getName();
System.out.println(attributeName + ": " + attributeVal);
}
// 4.循环根节点,获取其子节点
for (Iterator iter = rootElement.elementIterator(); iter.hasNext();) {
Element element = (Element) iter.next(); // 获取标签对象
// 5.获取第一层节点标签对象的属性:data
Attribute attr = element.attribute("ids");
if (null != attr) {
String attrVal = attr.getValue();
String attrName = attr.getName();
System.out.println(attrName + ": " + attrVal);
}
// 6.循环第二层节点,获取其子节点
for (Iterator iterInner = element.elementIterator(); iterInner.hasNext();) {
// 获取标签对象
Element elementOption = (Element) iterInner.next();
// 获取该标签对象的名称
String tagName = elementOption.getName();
// 获取该标签对象的内容
String tagContent = elementOption.getTextTrim();
// 输出内容
System.out.print(tagName + ": " + tagContent + " ");
//获取该标签属性:id...
Attribute atId = elementOption.attribute("id");
}
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
readXML();
}