Eagle
Eagle

Reputation: 3

I want to generate an XML file that does not need to be escaped if there are special characters

Using JDOM to generate an XML file, what is the best way to avoid escaping characters

enter image description here

I tried. I can't find a way

 public class JDomCreateXml {

    public static void main(String[] args) throws IOException {

        /**根节点*/
        Element rss = new Element("rss");
        rss.setAttribute("version", "2.0");

        /**创建document对象*/
        Document document = new Document(rss);

        /**添加子节点*/
        Element channel = new Element("channel");
        rss.addContent(channel);

        Element title = new Element("titlt");
        /**设置内容*/
        title.setText("<国内最新新闻>");
        rss.addContent(title);

        /**调节显示格式,规范格式*/
        Format format = Format.getPrettyFormat();
        format.setIndent("");
        format.setEncoding("GBK");

        /**利用xmlOutputter将document生成xml*/
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        xmlOutputter.output(document, new FileOutputStream(new File("jdom.xml")));
    }
}

I want to generate an XML file that does not need to be escaped if there are special characters

Upvotes: 0

Views: 180

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109532

The only way might be just even more cumbersome: a CDATA section.

For the text:

3 < 4 and 5 > 4

into

<p></p>

XML APIs convert the text automatically into:

<p>3 &lt; 4 and 5 &gt; 4</p>

On extraction using an XML API the entities will be unescaped again to the original text.

But with CDATA one can do:

   _________               ___
<p><![CDATA[3 < 4 and 5 > 4]]></p>

Using for instance org.w3c.Element then not add a Text child node, but a CDATASection child node.

The <[CDATA[ ... ]]> is used for raw text.

Upvotes: 3

Related Questions