Parsing process of creating XML (no Chinese garbled code) based on Java

This article mainly introduces the parsing process of creating XML (no Chinese garbled code) based on Java. It is introduced in great detail through the example code, which has a certain reference value for everyone's study or work. Friends in need can refer to it

package com.zyb.xml;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class TestXml2 {

  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    Document doc = DocumentHelper.createDocument();
    //1.创建根节点
    Element root = doc.addElement("books");
    for(int i=0;i<2;i++){
      //2.为根节点添加元素
      Element book = root.addElement("book");
      //3.如果有属性进行添加
      book.addAttribute("id","001");
      //4.为元素继续添加元素
      Element author = book.addElement("author");
      Element price = book.addElement("price");
      Element time = book.addElement("time");
      //5.给对应元素赋值
      author.addText("亚历山大");
      price.addText("12.25");
      time.addText("2015-09-05");
    }

    //良好的输出格式
    OutputFormat format = OutputFormat.createPrettyPrint();
    //6.//创建一个xml文件
    OutputStream out = new FileOutputStream("src/book2.xml");
    Writer wr = new OutputStreamWriter(out,"UTF-8");//用可改变编码的OutputStreamWriter代替了普通的FileWriter解决中文乱码问题
    XMLWriter output = new XMLWriter(wr,format);
    //7.将doc输出到xml文件中
    output.write(doc);
    //8.关闭资源
    wr.close();
    out.close();
    output.close();
  }

}

Operation results:

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>