Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding an xml document inside an xml string [duplicate]

Tags:

c#

xml

I have a web service that returns an xml string as results. The return string is in this format:

<ReturnValue>
   <ErrorNumber>0
</ErrorNumber>
<Message>my message</Message>
</ReturnValue>

The data that I want to insert into the "message" tag is a serialized version of a custom object. The serialized format of that object contains xml and namespace declarations post serialization. When that gets thrown into the "message" tag of my return xml string, XmlSpy says that it's not well-formed. How should I get rid of the namespace declarations, or is there a different way to imbed a serialized object into an xml string?

like image 448
ganders Avatar asked Nov 29 '11 19:11

ganders


2 Answers

Wrap the string in CDATA like so:

<![CDATA[your xml, which can be multi-line]]>

CDATA will inform a validator to treat the CDATA contents as ignored text. It's often the most expedient way to embed XML (or taggy non-XML content) as a string. You can run into problems if your embedded XML contains its own CDATA, but otherwise it's a simple fix.

like image 76
phatfingers Avatar answered Nov 07 '22 21:11

phatfingers


Just make sure that your <Message> XML is encoded so that <, >, ", and & show up as &lt;, &gt;, &quot; and &amp;, respectively.

There are few built-in ways to encode the characters:

string message = System.Web.HttpUtility.HtmlEncode(serializedXml);

string message = System.Security.SecurityElement.Escape(serializedXml);
  • Using an XmlTextWriter to do the work for you
  • Use CDATA to wrap your XML

Also, this is probably a duplicate of:

  1. Best way to encode text data for XML
like image 7
Cᴏʀʏ Avatar answered Nov 07 '22 23:11

Cᴏʀʏ