dom4j解析xml文件
2020-05-21 本文已影响0人
simplerandom
import java.io.File;
import java.util.Iterator;
import java.util.List;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
public class ParseXmlFile {
public static void main(String[] args) throws DocumentException {
File file = new File("members.xml");
// 创建SAXReader
SAXReader saxReader = new SAXReader();
// 将xml文件读入成document
Document document = saxReader.read(file);
// 使用xpath随机获取节点
// 获得student标签的集合
List<Node> list = document.selectNodes("/members/students/student");
// List<Node> list = xmlParser.getDocument().selectSingleNode("students");
// 遍历节点
Iterator<Node> iterator = list.iterator();
while(iterator.hasNext()) {
Element element = (Element)iterator.next();
// 获得标签名
System.out.println(element.getName());
// 获得属性的集合
List<Attribute> attributes = element.attributes();
for (Attribute attribute : element.attributes()) {
System.out.println(attribute.getName()+"-----"+attribute.getValue());
}
}
}
}