使用JDOM解析XML

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


	org.jdom
	jdom2
	2.0.6

使用到的demo.xml如下



    
        simons
              
        24
        
魔都
rose 22
帝都
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 elementList = rootElement.getChildren();
        for (Element element : elementList) {
            List attributes = element.getAttributes();
            for (Attribute attribute : attributes) {
                System.out.println(attribute.getName()+":"+attribute.getValue());
            }
            List 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

你可能感兴趣的:(Java,Java编程之路)