public void testDom4j(){
//读取XML文件,获得document对象
Document document = null;
try {
SAXReader saxReader = new SAXReader();
document = saxReader.read(this.getClass().getClassLoader().getResourceAsStream("student.xml"));
}catch (DocumentException e) {
e.printStackTrace();
}
//获取根节点
Element root = document.getRootElement();
// !获取子节点
List<Element> elements = rootElement.elements();
//获取节点属性-值
getNodes(root);
}
public static void getNodes(Element rootElement) {
System.out.println("标签名:"+rootElement.getName());
// 获取属性信息
List<Attribute> attributes = rootElement.attributes();
for (Attribute attribute : attributes) {
System.out.println("标签内属性:" + attribute.getName() + "---" + attribute.getText());
}
// 获取属性value
String value = rootElement.getTextTrim();
if (!StringUtils.isEmpty(value)) {
System.out.println("标签值:" + value);
}
System.out.println("——————————————");
// 使用迭代器遍历,继续遍历子节点
Iterator<Element> elementIterator = rootElement.elementIterator();
while (elementIterator.hasNext()) {
Element next = elementIterator.next();
getNodes(next);
}
}
更多可参考:
https://blog.csdn.net/p812438109/article/details/81814157
https://blog.csdn.net/qq_41860497/article/details/84339091#2.%205%E3%80%81%C2%A0%E9%81%8D%E5%8E%86xml%E8%8A%82%E7%82%B9