Jdom生成xml文件时的特殊字符问题(冒号,注释等)

import org.jdom.CDATA;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

    

public static String toXML(String path) throws IOException { Element root = new Element("ADI"); // 将根节点添加到文档中; Document Doc = new Document(root); CDATA text = null; // 创建节点 Element elements = new Element("Objects"); Element title = new Element("title"); title.setAttribute("Name", "title"); text = new CDATA(""); text.setText("125722130016"); title.setContent(text); object.addContent(title); Element vodfile = new Element("vodfile"); vodfile.setAttribute("Name", "vodfile"); vodfile.setText("<![CDATA[北125722130016.mp4]]>"); object.addContent(vodfile); root.addContent(elements); // 使xml文件 缩进效果 Format format = Format.getPrettyFormat(); XMLOutputter XMLOut = new XMLOutputter(format); XMLOut.output(Doc, new FileOutputStream(path)); return path; }

public static String toSpXML(String path) throws IOException {

Element root = new Element("ADI","tns","MREML");
root.addNamespaceDeclaration(Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
root.setAttribute("schemaLocation", "xsd", Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
// 将根节点添加到文档中;
Document Doc = new Document(root);

Element elements = new Element("Objects","tns","MREML");
Element object = new Element("Object","tns","MREML");
object.setAttribute("ElementType", "Program");
object.setAttribute("Action", "REGIST");
elements.addContent(object);
root.addContent(elements);
Format format = Format.getPrettyFormat();
XMLOutputter XMLOut = new XMLOutputter(format);
XMLOut.output(Doc, new FileOutputStream(path));
return path;
}

public static String toSp2XML(String path) throws IOException{
/*构建一个空的Document对象*/
Document doc = new Document();
/*创建一个注释*/
Comment comment = new Comment("一个学生信息文档");
/*将注释添加到文档中*/
doc.addContent(comment);
/*创建一个处理指令*/
ProcessingInstruction pi = new ProcessingInstruction("xml-stylesheet","type='text/css' href='students.css'");
/*将处理指令添加到文档中*/
doc.addContent(pi);
/*创建一个元素,名为student*/
Element root = new Element("student");
/*将student元素作为文档的根元素*/
doc.setRootElement(root);
/*为元素student添加一个属性,id为2013010111*/
Attribute attr = new Attribute("id","2013010111");
root.setAttribute(attr);
/*创建一个元素,名为name,设置内容为小田*/
Element eltName = new Element("name");
eltName.setText("小田");
Element eltDescrip = new Element("description");
CDATA cdata = new CDATA("最喜爱的图书《红楼梦》");
eltDescrip.setContent(cdata);

root.addContent(eltName);
root.addContent(eltDescrip);
/*将JDOM构建的Document对象作为字节流输出*/
XMLOutputter out = new XMLOutputter();
//格式化输出
Format fmt = Format.getPrettyFormat();
//设置编码格式
fmt.setEncoding("gb2312");
//设定缩进
fmt.setIndent(" ");
out.setFormat(fmt);
out.output(doc,new FileOutputStream(path));
return path;
}

 

compile 'org.jdom:jdom:1.1.3'

posted @ 2020-04-10 16:59  凉城  阅读(679)  评论(0编辑  收藏  举报