tags:

views:

859

answers:

2

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.

A: 

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

maxwellb
I did try, no go but other post got it, thanks.
typemismatch
+2  A: 

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");
}
Fredrik Mörk
THANKS!!!! great example, worked like a charm.I left your beer over here (b)
typemismatch
Hmm.. a bit late for beer here (bedtime, in fact). Can you put it in the fridge for the night? ;) (glad it worked out)
Fredrik Mörk