欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用JDOM解析XML

程序员文章站 2022-05-28 08:00:46
...

JDOM和DOM4J都不是Java官方提供的解析XML的工具包,因为使用JDOM前,你需要引入依赖

<dependency>
	<groupId>org.jdom</groupId>
	<artifactId>jdom2</artifactId>
	<version>2.0.6</version>
</dependency>

使用到的demo.xml如下

<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="person1" >
        <name>simons</name>
        <sex>男</sex>      
        <age>24</age>
        <address>魔都</address> 
	</person>
    <person id="person2" >
       <name>rose</name>
        <sex>女</sex>      
        <age>22</age>
        <address>帝都</address> 
	</person>
</persons>
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import java.io.File;
import java.util.List;

public class JDOMParseXml {

    public static void main(String[] args) throws Exception {
        SAXBuilder saxBuilder = new SAXBuilder();
        //你也可以将demo.xml放在resources目录下,然后通过下面方式获取
        //InputStream resourceAsStream = JDOMParseXml.class.getClassLoader().getResourceAsStream("demo.xml");
        Document document = saxBuilder.build(new File("D:/demo.xml"));
        Element rootElement = document.getRootElement();
        List<Element> elementList = rootElement.getChildren();
        for (Element element : elementList) {
            List<Attribute> attributes = element.getAttributes();
            for (Attribute attribute : attributes) {
                System.out.println(attribute.getName()+":"+attribute.getValue());
            }
            List<Element> children = element.getChildren();
            for (Element child : children) {
                System.out.println(child.getName()+":"+child.getValue());
            }
        }
    }

}

输出结果如下

id:person1
name:simons
sex:男
age:24
address:魔都
id:person2
name:rose
sex:女
age:22
address:帝都

引申阅读:

使用SAX解析XML:https://blog.csdn.net/fanrenxiang/article/details/81098041

使用DOM4J解析XML:https://blog.csdn.net/fanrenxiang/article/details/81099346

使用DOM解析XML:https://blog.csdn.net/fanrenxiang/article/details/81078854

相关标签: 使用JDOM解析XML