Question

I have an xml with the following structure:

<rootNode>
<category name="test1">
    <string name="n1">n1</string>
    <string name="n2"><![CDATA[n2]]></string>
    <string name="n3">&lt;&lt;n3</string>
</category>
<category name="test2">
    <string name="n111">n111</string>
    <string name="n2"><![CDATA[&lt;&lt;n2]]></string>
    <string name="n3 &amp;">
        <![CDATA[n3
        multiline]]>
    </string>
</category>

rootNode has multiple category nodes, with multiple "string" nodes. Need to make all nodes CDATA. All my attempts failed, especially because of the nodes from "test2" (change node.InnerText, parse text with string.Replace etc.)

expected result:

<rootNode>
<category name="test1">
    <string name="n1"><![CDATA[n1]]></string>
    <string name="n2"><![CDATA[n2]]></string>
    <string name="n3"><![CDATA[<<n3]]></string>
</category>
<category name="test2">
    <string name="n111"><![CDATA[n111]]></string>
    <string name="n2"><![CDATA[&lt;&lt;n2]]></string>
    <string name="n3 &amp;">
        <![CDATA[n3
        multiline]]>
    </string>
</category>

Was it helpful?

Solution

You can try this way :

var doc = new XmlDocument();
doc.Load("path_to_xml_file.xml");
var elements = doc.DocumentElement.SelectNodes("/rootNode/category/string");
foreach (XmlNode element in elements)
{
    //check if content of <string> is not CData section
    if(!(element.FirstChild is XmlCDataSection))
    {
        XmlCDataSection cdata = doc.CreateCDataSection(element.InnerText);
        //replace inner text with CData section
        element.ReplaceChild(cdata, element.FirstChild);
    }
}

doc.Save("path_to_xml_file.xml");

OTHER TIPS

    private void AddCData(string path) {
        XmlDocument doc = new XmlDocument();
        doc.Load(path);
        XmlNode root = doc.DocumentElement;
        foreach (XmlNode childNode in root.SelectNodes("/rootNode/category/string")) {
            AddCData(childNode);
        }
        doc.Save(path + "_output.xml");
    }

    private void AddCData(XmlNode node) {
        string innerText = node.InnerText;
        if (!string.IsNullOrEmpty(innerText)) {
            if (!innerText.StartsWith("<![CDATA[")) {
                var newCDATA = node.OwnerDocument.CreateCDataSection(innerText);
                node.InnerText = "";
                node.AppendChild(newCDATA);
            }
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top