简体   繁体   中英

Stop CDATA tags from being output-escaped when writing to XML in C#

We're creating a system outputting some data to an XML schema. Some of the fields in this schema need their formatting preserved, as it will be parsed by the end system into potentially a Word doc layout. To do this we're using <![CDATA[Some formatted text]]> tags inside of the App.Config file, then putting that into an appropriate property field in a xsd.exe generated class from our schema. Ideally the formatting wouldn't be out problem, but unfortunately thats just how the system is going.

The App.Config section looks as follows:

<header>
<![CDATA[Some sample formatted data]]>
</header>

The data assignment looks as follows:

HeaderSection header = ConfigurationManager.GetSection("header") as HeaderSection;
report.header = "<[CDATA[" + header.Header + "]]>";

Finally, the Xml output is handled as follows:

xs = new XmlSerializer(typeof(report));
fs = new FileStream (reportLocation, FileMode.Create);
xs.Serialize(fs, report);
fs.Flush();
fs.Close();

This should in theory produce in the final Xml a section that has information with CDATA tags around it. However, the angled brackets are being converted into &lt; and &gt;

I've looked at ways of disabling Outout Escaping, but so far can only find references to XSLT sheets. I've also tried @"<[CDATA[" with the strings, but again no luck.

Any help would be appreciated!

You're confusing markup with content.

When you assign the string "<![CDATA[ ... ]]>" to the value, you are saying that is the content that you wish to put in there. The XmlSerializer does not, and indeed should not, attempt to infer any markup semantics from this content, and simply escapes it according to the normal rules.

If you want CDATA markup in there, then you need to explicitly instruct the serializer to do so. Some examples of how to do this are here .

Have you tried changing

report.header = "<[CDATA[" + header.Header + "]]>";

to

report.header = "<![CDATA[" + header.Header + "]]>";

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