Dom4j escape character formatting

Source: Internet
Author: User

Dom4j escape character formatting1. xml cdata parts that have to be mentionedAll text in the XML document will be parsed by the parser. Only the text in the CDATA part is ignored by the parser. Invalid XML characters must be replaced with corresponding entities. If you use a character similar to "<" in the XML document, the parser will encounter an error because the parser considers this as the beginning of a new element.

& Lt; < Yu no.
& Gt; > Yu no.
& Amp; & And
& Apos; ' Single quotes
& Quot; " Double quotation marks

The object must start with the symbol "&" and end with the symbol.
Note: Only the "<" and "&" characters are strictly forbidden for XML. The rest are legal. It is a good habit to use entities to reduce errors.
CDATA parts
All content in CDATA is ignored by the parser. If the text contains many "<" characters and "&" characters-like program code, it is best to put them in the CDATA component. A CDATA part starts with "<! [CDATA ["Mark start, end with"]> "mark:
CDATA considerations:
CDATA components cannot be nested ). If the CDATA part contains the character "]>" or "<! [CDATA [", which may cause errors. Note that there is no space or line break between the string "]>. 2. Question about Dom4j formatting escape characters: person. xml <? Xml version = "1.0" encoding = "UTF-8"?>
<Person>
<Name> Zhang San </name>
<Addr> <! [CDATA [Jingsan road <Xinyuan> 19F]> </addr>
</Person> the above XML is automatically escaped when formatted by Dom4j. The escaped content is as follows: <? Xml version = "1.0" encoding = "GBK"?> <Person>
<Toname> & lt ;! [CDATA [Jingsan Road & lt; Xinyuan & gt; 19F] & gt; </toname>
</Person>
In this way, it is clearly not the desired result, because CDATA does not need to be escaped. To solve this problem, see the following program: import org. dom4j. Document;
Import org. dom4j. DocumentHelper;
Import org. dom4j. Element;
Import org. dom4j. io. OutputFormat;
Import org. dom4j. io. XMLWriter;

Import java. io. IOException;
Import java. io. StringWriter;
Import java. util. Date;

/**
* Created by IntelliJ IDEA.
*
* @ Author leizhimin 2010-7-10 16:03:39
*/
Public class Person {
Private String name;
Private String addr;

Public Person (String name, String addr ){
This. name = name;
This. addr = addr;
}

Public static void main (String [] args ){
Person p = new Person ("Zhang San", "Jing San Road <Xin Yuan> 19F ");
P. showXml ();
}

Public void showXml (){
String xml1, xml2, xml3;
Document doc = incluenthelper. createDocument ();
Doc. setXMLEncoding ("GBK ");
Element root = doc. addElement ("person ");
If (addr! = Null)
AddElement (root, "toname", "<! [CDATA ["+ this. addr +"]> ");
Else
AddElement (root, "toname", this. addr );

Xml1 = doc. asXML (); // default escape
Xml2 = formatXml (doc, "GBK", true); // escape
Xml3 = formatXml (doc, "GBK", false); // do not escape
System. out. println (xml1 );
System. out. println ("-------------------------");
System. out. println (xml2 );
System. out. println ("-------------------------");
System. out. println (xml3 );
}

/**
* Add a new child element to the specified element.
*
* @ Param e parent Element
* @ Param name sub-element name
* @ Param value child element value
* @ Return Add a child element
*/
Public static Element addElement (Element e, String name, Object value ){
Element x = e. addElement (name );
If (value = null | "". equals (value. toString (). trim ())){
X. setText ("");
} Else if (value instanceof Date ){
X. setText (datemedilkit. toISOFormat (Date) value ));
} Else {
X. setText (value. toString ());
}
Return x;
}

/**
* Format an XML document
*
* @ Param document xml document
* @ Param charset string Encoding
* @ Param istrans: whether to transfer attributes and element values
* @ Return formatted XML string
*/
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 ("an exception occurred when formatting the XML document. Please check! ");
E. printStackTrace ();
}
Return sw. toString ();
}
} Output result: <? Xml version = "1.0" encoding = "GBK"?>
<Person> <toname> & lt ;! [CDATA [Jingsan Road & lt; Xinyuan & gt; 19F] & gt; </toname> </person>
-------------------------
<? Xml version = "1.0" encoding = "GBK"?> <Person>
<Toname> & lt ;! [CDATA [Jingsan Road & lt; Xinyuan & gt; 19F] & gt; </toname>
</Person> -------------------------
<? Xml version = "1.0" encoding = "GBK"?> <Person>
<Toname> <! [CDATA [Jing San Road <Xinyuan> 19F]> </toname>
</Person>
Process finished with exit code 0 shows that the last output is the expected result. Therefore, to control the escape, you must reformat the XML. During formatting, you must set the following parameters: Xw. setEscapeText (false );

This article is from the "melyan" blog, please be sure to keep this source http://lavasoft.blog.51cto.com/62575/347348

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.