import org.dom4j.Document;
import org.dom4j.DocumentHelper;
public class DOM {
public static void main(String[] args) throws Exception {
Document doc = DocumentHelper.parseText("<root>"</root>");
System.out.println(doc.asXML());
}
}
get results:
<?xml version="1.0" encoding="UTF-8"?>
<root>"</root>
I hope that does not handle escape characters can get:
<?xml version="1.0" encoding="UTF-8"?>
<root>"</root>
No matter where I read from xml , or a string , escape characters will change , I hope it will not deal with the escape character , so do not write to the xml file processing . How to do it .
------ Solution ------------------------------------ --------
/ / another way to add transcoding xml file
OutputFormat format = OutputFormat.createPrettyPrint ();
format.setEncoding ("UTF-8");
XMLWriter writer = new XMLWriter (new FileOutputStream ("src / book.xml"), format);
writer.write (document);
writer.close ();
}
original source : http://blog.csdn.net/tianyazaiheruan/article/details/8065722
------ Solution ---------------- ----------------------------
import java.io.IOException;
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;
public class Test {
public static void main (String [] args) throws Exception {
Document doc = DocumentHelper.createDocument ();
doc.setXMLEncoding ("GBK");
Element root = doc.addElement ("root");
root.addText (""");
/ / Document doc = DocumentHelper.parseText ("
System.out.println (doc.asXML ());
System.out.println (Test.formatXml (doc, "utf-8", false));
}
/ **
* formatting XML documents
*
* @ param document xml document Coding
* @ param charset string Are
* @ param istrans values of attributes and elements transfer
* @ return string formatted XML
* /
public static String formatXml (Document document, String charset, boolean istrans) {
OutputFormat format = OutputFormat.createPrettyPrint ();
format.setEncoding (charset);
StringWriter sw = new StringWriter ();
XMLWriter xw = new XMLWriter (sw, format);
xw.setEscapeText (istrans);
try {
xw.write (document) ;
xw.flush ();
xw.close ();
} catch (IOException e) {
System.out.println ( " formatting XML document exception occurs, please check ! " ) ;
e.printStackTrace ();
}
return sw.toString ();
}
}
------ For reference only --------------------------------- ------
I have encountered this problem , the landlord solved? Solve the trouble to share , thank you ! Other emergency
没有评论:
发表评论