使用C#的XML中的CDATA

时间:2009-06-05 21:42:31

标签: c# xml xpath

这是一种不寻常的情况。我们被迫与需要xml响应中某些值的第三方交互,即使它只是一个字符串值。

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

我们将这些属性节点添加到文档中,如下所示:

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);

问题是,生成的xml看起来像这样

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

CDATA一直被剥夺。

2 个答案:

答案 0 :(得分:3)

您可以使用XmlWriter写入数据来实现此目的:

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");
}

答案 1 :(得分:0)

您可能想要检查node.AppendChild()。WriteRaw(property)是否可行,因为您似乎还是手动格式化XML字符串。