package com.test;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.StringReader;
import java.util.List;
/**
* Created by admin on 2018/7/17.
*/
public class test {
public static void main(String[] args) {
String xmlString = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<root>" +
"<user>" +
"<name>张三</name>" +
"<year>24</year>" +
"<sex>男</sex>" +
"<hobby>" +
"<hobby1>运动</hobby1>" +
"<hobby2>听歌</hobby2>" +
"</hobby>" +
"</user>" +
"<user>" +
"<name>李四</name>" +
"<year>24</year>" +
"<sex>女</sex>" +
"</user>" +
"</root>";
try {
SAXReader sax = new SAXReader();//创建一个SAXReader对象
StringReader read = new StringReader(xmlString);
Document document = sax.read(read);//获取document对象,如果文档无节点,则会抛出Exception提前结束
Element root = document.getRootElement();//获取根节点
System.out.println(root.getName());
getNodes(root);
} catch (Exception e) {
}
}
public static void getNodes(Element root) {
System.out.println("--------------------");
//当前节点的名称、文本内容和属性
System.out.println("当前节点名称:" + root.getName());//当前节点名称
System.out.println("当前节点的内容:" + root.getTextTrim());//当前节点名称
//获取根节点下面的所有子节点(不包过子节点的子节点)
List<Element> list = root.elements();
//遍历List的方法
for (Element e : list) {
if ("".equals(e.getTextTrim())) {
getNodes(e);
} else {
System.out.println("节点名称:" + e.getName() + " 属性值:" + e.getTextTrim());
}
}
}
}
java解析xml字符串——SAX(Simple API for XML)
最新推荐文章于 2024-09-24 17:54:17 发布