简体   繁体   中英

Java output XML file and CDATA

I am having a problem with the javax.xml.transform.Transformer class and its setOutputProperty method. I'm trying to get a XML output

   <name>
  <text>XXXXXXXXXX</text>
</name>
<questiontext format="html">
  <text><![CDATA[YYYYYYYYYYY]]></text>
</questiontext>

But using the:

        Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "text");

causes for the both of text nodes to be embedded by CDATA tags like so:

    <name>
  <text><![CDATA[XXXXXXXXXX]]></text>
</name>
<questiontext format="html">
  <text><![CDATA[YYYYYYYYYYY]]></text>
</questiontext>

So i guess i need a way to specify the parent of the text element but i haven't found a way to do so and the javadocs don't specify which notation is used. Also i am not in a position to change the output XML format.

You can't - the OutputKeys.CDATA_SECTION_ELEMENTS output property corresponds to the XSLT cdata-section-elements attribute of <xsl:output> , and that only allows you to define the elements in terms of QNames, not match expressions.

But it shouldn't matter since <foo>text</foo> and <foo><![CDATA[text]]></foo> are identical as far as an XML parser is concerned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM