dom4j生成/解析xml文件

解析

1.引入依赖

<!-- dom4j -->
<dependency>
  <groupId>org.dom4j</groupId>
  <artifactId>dom4j</artifactId>
  <version>2.1.0</version>
</dependency>

2.需要解析的xml文件

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="imooc-001" category="历史">
        <name>三国演义</name>
        <author>罗贯中</author>
        <price>1030</price>
    </book>
    <book id="imooc-002" category="编程">
        <name>Oracle开发实战经典</name>
        <author>李兴华</author>
        <price>60</price>
    </book>
</books>

3.该xml文件所对应的JavaBean

public class Book {
    private String id;
    private String category;
    private String name;
    private String author;
    private int price;
    //get和set方法
}

4.编写读取Dom对象的工具类Dom4jReaderUtils

public class Dom4jReaderUtils {
    public static Document getDocument() {
        String resource = "/Volumes/TOSHIBA EXT/1.学习/代码/6.SSM/springmvc/springMVC_demo/src/main/resources/file/books.xml";
        Document document = null;
        SAXReader reader = new SAXReader();
        try {
            document = reader.read(new File(resource));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return document;
    }
}

5.编写写入DOM对象的工具类Dom4jWriterUtils

//编写写入DOM对象的工具类Dom4jWriterUtils
public class Dom4jWriterUtils {
    public static void writeDom(Document document) throws IOException {
        //创建文件输出的时候,自动缩进的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = null;
        try {
            //设置编码
            format.setEncoding("UTF-8");
            //创建XMLWriter对象的时候,为防止乱码最好传入FileOutStream作为参数
            writer = new XMLWriter(new FileOutputStream(new File("/Volumes/TOSHIBA EXT/1.学习/代码/6.SSM/springmvc/springMVC_demo/src/main/resources/file/Mapper.xml")), format);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.编写Dom4jCRUD实现对books.xml进行读取并进行测试

public class Dom4jCURD {
    public static void main(String[] args) {
        //读取books文件中的内容
        Document document = Dom4jReaderUtils.getDocument();
        List<Book> bookList=getBookListFromXML(document);
        Iterator<Book> iterator = bookList.iterator();
        while(iterator.hasNext()){
            Book book = iterator.next();
            System.out.println("id:"+book.getId());
            System.out.println("category:"+book.getCategory());
            System.out.println("author:"+book.getAuthor());
            System.out.println("name:"+book.getName());
            System.out.println("price:"+book.getPrice());
        }
    }
    /**
     * 读取xml文件中所有的book子节点并将其封装成Book对象放在List中返回。
     * @param document XML文档对象
     * @return 存放Book对象的List
     */
    public static List<Book> getBookListFromXML(Document document) {
        List<Book> bookList = new ArrayList<Book>();
        Element root = document.getRootElement();
        Iterator<Element> bookIterator = root.elementIterator();
        while (bookIterator.hasNext()) {
            Element element = bookIterator.next();
            Book book = new Book();
            book.setName(element.elementText("name"));
            book.setPrice(Integer.parseInt(element.elementText("price")));
            book.setAuthor(element.elementText("author"));
            Iterator<Attribute> bookAttr = element.attributeIterator();
            while (bookAttr.hasNext()) {
                Attribute attribute = bookAttr.next();
                String attributeName = attribute.getName();
                if (attributeName.equals("id")) {
                    book.setId(attribute.getValue());
                } else {
                    book.setCategory(attribute.getValue());
                }
            }
            bookList.add(book);
        }
        return bookList;
    }
}

生成

1.引入依赖

<!-- dom4j -->
<dependency>
  <groupId>org.dom4j</groupId>
  <artifactId>dom4j</artifactId>
  <version>2.1.0</version>
</dependency>

2.编写生成xml文件内容的代码

class Dom4JTest {

    public static void main(String[] args) throws FileNotFoundException {
        createXMLFile();
    }

    /**
     *使用Dom4J创建一个新的XML文档
     */
    public static void createXMLFile() throws FileNotFoundException {
        //1.创建一个xml文档
        Document document = DocumentHelper.createDocument();
        //2.创建一个根元素,并为其设置属性
        Element root = DocumentHelper.createElement("mapper");
        root.addAttribute("namespace","com.steven.ssm.mapper.ItemsMapperCustom");
        //3.为根元素创建子节点,并设置属性和值
        document.setRootElement(root);
        Element select = DocumentHelper.createElement("select");
        select.addAttribute("id","getItemsList").addAttribute("resultMap","queryItems").addText("select *  from items");
        root.add(select);
        Element resultMap = DocumentHelper.createElement("resultMap");
        resultMap.addAttribute("id","queryItems").addAttribute("type","items");
        root.add(resultMap);
        
        Element id = resultMap.addElement("id");
        id.addAttribute("column","item_id").addAttribute("property","itemId");
        Element itemName = resultMap.addElement("itemName");
        itemName.addAttribute("column","item_name").addAttribute("property","itemName");

        //4.将文档内容写入指定的xml文件中
        Dom4jWriterUtils.writeDom(document);
    }
}

3.生成的xml文件

<?xml version="1.0" encoding="UTF-8"?>

<mapper namespace="com.steven.ssm.mapper.ItemsMapperCustom">
  <select id="getItemsList" resultMap="queryItems">select * from items</select>
  <resultMap id="queryItems" type="items">
    <id column="item_id" property="itemId"/>
    <itemName column="item_name" property="itemName"/>
  </resultMap>
</mapper>

猜你喜欢

转载自blog.csdn.net/u010286027/article/details/85234948
今日推荐