在 java注解生成xml和包含CDATA问题里面做了介绍,这里直接贴代码。
1:生成xml的java文件
package com.dufy.test.xml;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
/**
* 使用DOM4J生成xml并包括CDATA的处理
* @author aflyun
* @date 2016.06.16
*
*/
public class TestGenerateXml {
/**
* @param args
*/
public static void main(String[] args) {
loadXml();
}
/**
* 生成 document xml
*/
public static void loadXml(){
Document document = DocumentHelper.createDocument();//由DocumentHelper得到一个空的Document
document.setXMLEncoding("utf-8");//设置xml头条的Encoding
//addElement写入根节点 addAttribute节点属性的键和值
Element root = document.addElement("item");//.addAttribute("xmlns", "").addAttribute("版本号", "");
//由根节点 可以得到下二级的节点
Element id = root.addElement("id");
id.addText("35399645973");
//二级节点
Element title = root.addElement("title");
title.addText("<![CDATA[补水首选水密码水保湿美白护洗护组合三件]]>");
Element category = root.addElement("category");
category.addText("<![CDATA[美妆>保湿>洗护]]>");
Element url = root.addElement("url");
url.addText("<![CDATA[http://www.example.com/detail-35399645973]]>");
Element url_wap = root.addElement("url_wap");
url_wap.addText("<![CDATA[http://www.example.com/detail-35399645973]]>");
Element price = root.addElement("price");
price.addText("310");
Element promotion_price = root.addElement("promotion_price");
promotion_price.addText("111");
Element wap_price = root.addElement("wap_price");
wap_price.addText("80");
Element sub_item_ids = root.addElement("sub_item_ids");
Element sub_item_id = sub_item_ids.addElement("sub_item_id");
sub_item_id.addText("35399645973_1");
sub_item_id.addText("35399645973_2");
sub_item_id.addText("35399645973_3");
Element detail = root.addElement("<detail>");
detail.addText("<![CDATA[商品详情,支持html图文混排]]>");
Element status = root.addElement("status");
status.addText("1");
Element pic_main = root.addElement("pic_main");
Element img_main = pic_main.addElement("img");
img_main.addElement("url").addText("<![CDATA[http://www.example.com/10777829/T_400x400.jpg]]>");
img_main.addElement("size").addText("400x400");
Element pic_extra = root.addElement("pic_extra");
Element img_extra = pic_extra.addElement("img");
img_extra.addElement("url").addText("<![CDATA[http://www.example.com/10777829/T_400x400.jpg]]>");
img_extra.addElement("size").addText("400x400");
Element img_extr1 = pic_extra.addElement("img");
img_extr1.addElement("url").addText