Dom4j解析XML的元素,文本,属性(API)

86 阅读1分钟

image.png

image.png

public class FileDemo {
    public static void main(String[] args) throws Exception {
        SAXReader saxReader = new SAXReader();//SAXReader()获取解析器对象
        InputStream is = FileDemo.class.getResourceAsStream("/app.xml");//得到xml文件的字节输入流
        Document document = saxReader.read(is);//将xml文件转成Document文件
        Element root = document.getRootElement();//得到根元素对象
        System.out.println(root.getName());

      // List<Element> sonElement = root.elements(); //elements(); 得到当前元素下所有子元素返回集合
       List<Element> sonElement =  root.elements("contact");//elements(String name); 得到当前元素下指定名字的子元素返回集合
        for (Element element : sonElement) {
            System.out.println(element.getName());//getName(); 得到元素名字
        }

        Element userEle = root.element("user");//element(String name) 得到当前元素下的指定名字的子元素 如果有很多名字相同的返回第一个
        System.out.println(userEle.getName());

        Element contact = root.element("contact");
        System.out.println(contact.elementText("name"));//获取子元素文本
        System.out.println(contact.elementTextTrim("name"));//获取子元素文本,去掉前后空格
        Element email = contact.element("email");//获取当前元素下的子元素对象
        System.out.println(email.getText());//获取文本 

        Attribute vipAttr = contact.attribute("vip"); //attribute(String name) 得到指定名字的属性对象
        System.out.println(vipAttr.getName() + "->" + vipAttr.getValue());//获取属性对象的名字和值
        System.out.println("id" + "->" + contact.attributeValue("id"));//直接获取指定名字的属性对象的值
    }
}