typemismatch
typemismatch

Reputation: 2058

CDATA in XML using C#

This is an unusual situation. We are forced to interface with a 3rd party who requires certain values in the xml response to be wrapped with even if it is just a string value.

Example: <Property name="someName" type="String"><![CDATA[someValue]]></Property>

We are adding these property nodes to the document as follows:

XPathExpression query = xPathNavigator.Compile(xpath);

XPathNavigator node = xPathNavigator.SelectSingleNode(query.Expression, xmlNamespaceManager);

string property = "<Property name='someName' type='String'><![CDATA[someValue]]></Property>";

node.AppendChild(property);

The problem is, the resulting xml looks like this

<Property name="someName" type="String">someValue</Property>

The CDATA keeps getting stripped out.

Upvotes: 0

Views: 5701

Answers (2)

Fredrik M&#246;rk
Fredrik M&#246;rk

Reputation: 158389

You can achieve this by using an XmlWriter to write the data:

private static void WriteProperty(XmlWriter writer, string name, string type, string value)
{
    writer.WriteStartElement("Property");
    writer.WriteAttributeString("name", name);
    writer.WriteAttributeString("type", type);
    writer.WriteCData(value);
    writer.WriteEndElement();

}

// call the method from your code
XPathExpression query = xPathNavigator.Compile(xpath);    
XPathNavigator node = xPathNavigator.SelectSingleNode(query.Expression, xmlNamespaceManager);
using (XmlWriter writer = node.AppendChild())
{
    WriteProperty(writer, "someName", "String", "someValue");
}

Upvotes: 3

maxwellb
maxwellb

Reputation: 13964

You might want to check if node.AppendChild().WriteRaw(property) will work, given that you seem to be formatting the XML string manually anyway.

Upvotes: 0

Related Questions