• java dom4j xml生成,解析


    1. 用Java代码生成xml文档

    package com.test.dom;
    
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.XMLWriter;
    
    public class Dom4jDemo {
    
        public static void main(String[] args) throws IOException {
            Document doc = DocumentHelper.createDocument();
            Element root = DocumentHelper.createElement("books");
    
            doc.setRootElement(root);
            root.addAttribute("id", "001");
            Element bookElement = root.addElement("book");
            Element titleElement = bookElement.addElement("title");
            titleElement.setText("Harry Potter");
    
            Element authorElement = bookElement.addElement("author");
            authorElement.setText("J K. Rowling");
    
            // 输出到控制台中
            XMLWriter xmlWriter = new XMLWriter();
            xmlWriter.write(doc);
    
            // 把生成的xml文档存放在硬盘上 true代表是否换行
            OutputFormat format = new OutputFormat("    ", true);
            format.setEncoding("GBK");// 设置编码格式
            XMLWriter fileXmlWriter = new XMLWriter(new FileOutputStream("e:/books.xml"), format);
    
            fileXmlWriter.write(doc);
            fileXmlWriter.close();
        }
    }

    xml结构

    <?xml version="1.0" encoding="GBK"?>
    <books id="001">
        <book>
            <title>Harry Potter</title>
            <author>J K. Rowling</author>
        </book>
    </books>

     2. 解析xml

       从String中获取

    String xmlStr = "<books>......</books>";  
    Document document = DocumentHelper.parseText(xmlStr); 

       从文件中获取

    //创建SAXReader对象  
     SAXReader reader = new SAXReader();  
    //读取文件 转换成Document  
      Document document = reader.read(new File("books.xml"));
  • 相关阅读:
    Fedora安装ati显卡驱动
    [转]SQLite 3入门教程
    [转]QT:不规则窗口的实现
    Ubuntu 10.10可用源
    [转]Qtopia2.2.0移植
    [转]嵌入式Qtopia2.2.0开发环境的搭建和使用
    ES6 find 和 filter 的区别
    “/ArcGIS/rest”应用程序中的服务器错误——解决办法
    Java:String和Date、Timestamp之间的转换
    UVA 100 The 3n+1 Problem
  • 原文地址:https://www.cnblogs.com/newlangwen/p/7708783.html
Copyright © 2020-2023  润新知