Java操作XML(5)--使用JDOM处理XML

    JDOM是一个开源项目,它基于树型结构,利用纯JAVA的技术对XML文档实现解析、生成、序列化以及多种操作。本文主要介绍使用JDOM来处理XML,文中所使用到的软件版本:Java 1.8.0_191、JDOM 2.0.6。

1、前言

    W3C在设计DOM模型时,并不是针对某一种语言而设计,因此为了通用性,加入了许多繁琐而不必要的细节 ,使JAVA程序员在开发XML的应用程序过程中感到不甚方便,因此JDOM作为一种新型的XML解析器应运而生,它不遵循DOM模型,建立了自己独立的一套JDOM模型(注意JDOM决不是DOM扩展,虽然名字差不多,但两者是平行的关系),并提供功能强大使用方便的类库,使JAVA程序员可以更为高效的开发自己的XML应用程序,并极大的减少了代码量。

2、使用JDOM操作XML

2.1、XML文件

<?xml version="1.0" encoding="utf-8" ?>
<school:grade xmlns:school="http://www.w3.org/TR/html4/school/">
    <school:student rollno="1" school:age="10">
        <school:firstname>cxx1</school:firstname>
        <lastname>Bob1</lastname>
        <nickname>stars1</nickname>
        <marks>85</marks>
    </school:student>
    <student rollno="2">
        <firstname>cxx2</firstname>
        <lastname>Bob2</lastname>
        <nickname>stars2</nickname>
        <marks>85</marks>
    </student>
    <student rollno="3">
        <firstname>cxx3</firstname>
        <lastname>Bob3</lastname>
        <nickname>stars3</nickname>
        <marks>85</marks>
    </student>
</school:grade>

2.2、引入依赖

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

2.3、Java代码例子

该例子演示了使用JDOM解析XML、JDOM中XPath的使用以及使用JDOM来生成XML。

package com.abc.demo.general.xml;

import org.jdom2.*;
import org.jdom2.filter.Filter;
import org.jdom2.filter.Filters;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.jdom2.xpath.XPathBuilder;
import org.jdom2.xpath.XPathExpression;
import org.jdom2.xpath.XPathFactory;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * 使用JDOM处理xml
 */
public class JDomCase {
    private static Logger logger = LoggerFactory.getLogger(DomCase.class);

    /**
     * 解析xml
     * @throws Exception
     */
    @Test
    public void parse() throws Exception {
        SAXBuilder sb = new SAXBuilder();
        Document document = sb.build(DomCase.class.getResourceAsStream("student.xml"));
        Element root = document.getRootElement();

        Namespace namespace = Namespace.getNamespace("school", "http://www.w3.org/TR/html4/school/");
        List<Element> list = root.getChildren("student", namespace);//第1位学生
        for (int i = 0; i < list.size(); i++) {
            Element student = list.get(i);
            logger.info("学生编号{}", student.getAttributeValue("rollno"));
            logger.info("age:{}", student.getAttributeValue("age", namespace));
            logger.info("firstname:{}", student.getChildText("firstname", namespace));
            logger.info("lastname:{}", student.getChildText("lastname"));
            logger.info("nickname:{}", student.getChildText("nickname"));
            logger.info("marks:{}", student.getChildText("marks"));
        }

        list = root.getChildren("student");//第2、3位学生
        for (int i = 0; i < list.size(); i++) {
            Element student = list.get(i);
            logger.info("学生编号{}",student.getAttributeValue("rollno"));
            logger.info("firstname:{}", student.getChildText("firstname"));
            logger.info("lastname:{}", student.getChildText("lastname"));
            logger.info("nickname:{}", student.getChildText("nickname"));
            logger.info("marks:{}", student.getChildText("marks"));
        }
    }

    /**
     * xpath使用
     * @throws Exception
     */
    @Test
    public void xpath() throws Exception {
        SAXBuilder sb = new SAXBuilder();
        Document document = sb.build(DomCase.class.getResourceAsStream("student.xml"));
        Namespace namespace = Namespace.getNamespace("school", "http://www.w3.org/TR/html4/school/");

        Filter<Text> filter = Filters.text();
        logger.info("查找所有的存在rollno属性的student节点,取出lastname的值");
        XPathBuilder<Text> builder = new XPathBuilder<Text>("//student[@rollno]/lastname/text()", filter);//第2、3位学生
//        XPathBuilder<Text> builder = new XPathBuilder<Text>("//student[@rollno]/child::lastname/text()", filter);//效果同上
//        XPathBuilder<Text> builder = new XPathBuilder<Text>("//school:student[@rollno]/lastname/text()", filter);//第1位学生
        builder.setNamespace(namespace);
        XPathExpression<Text> expression = builder.compileWith(XPathFactory.instance());
        //XPathExpression<Object> expression = XPathFactory.instance().compile("//student[@rollno]/lastname/text()");
        List<Text> list = expression.evaluate(document);
        for (int i = 0; i < list.size(); i++) {
            Text text = list.get(i);
            logger.info(text.getText());
        }
    }

    /**
     * 生成xml
     */
    @Test
    public void toXml() throws Exception {
        Document document = new Document();
        Namespace namespace = Namespace.getNamespace("school", "http://www.w3.org/TR/html4/school/");
        Element root = new Element("class", namespace);
        document.setRootElement(root);
        //第一个学生
        Element student = new Element("student", namespace);
        student.setAttribute(new Attribute("rollno", "1"));
        student.setAttribute(new Attribute("age", "10", namespace));
        Element firstname = new Element("firstname", namespace).setText("cxx1");
        Element lastname = new Element("lastname").setText("Bob1");
        Element nickname = new Element("nickname").setText("stars1");
        Element marks = new Element("marks").setText("85");

        student.addContent(firstname);
        student.addContent(lastname);
        student.addContent(nickname);
        student.addContent(marks);
        root.addContent(student);

        //第二个学生
        student = new Element("student");
        student.setAttribute(new Attribute("rollno", "2"));
        firstname = new Element("firstname", namespace).setText("cxx2");
        lastname = new Element("lastname").setText("Bob2");
        nickname = new Element("nickname").setText("stars2");
        marks = new Element("marks").setText("85");

        student.addContent(firstname);
        student.addContent(lastname);
        student.addContent(nickname);
        student.addContent(marks);
        root.addContent(student);

        //第三个学生
        student = new Element("student");
        student.setAttribute(new Attribute("rollno", "3"));
        firstname = new Element("firstname", namespace).setText("cxx3");
        lastname = new Element("lastname").setText("Bob3");
        nickname = new Element("nickname").setText("stars3");
        marks = new Element("marks").setText("85");

        student.addContent(firstname);
        student.addContent(lastname);
        student.addContent(nickname);
        student.addContent(marks);
        root.addContent(student);

        XMLOutputter xmlOutput = new XMLOutputter();
        //xml格式化
        Format format = Format.getRawFormat();
        //文本缩进
        format.setIndent("  ");
        format.setTextMode(Format.TextMode.TRIM_FULL_WHITE);
        xmlOutput.setFormat(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutput.output(document, out);
        logger.info(out.toString());
    }
}

 

posted @ 2020-12-20 15:56  且行且码  阅读(401)  评论(0编辑  收藏  举报