Search code examples
c#linq-to-xmlxelement

Insert XElement in XCData


I'm modifying an XML generator script that pulls data from a Sharepoint list, and generates XML from it.

One section of the XML looks like:

<node>
    <node2>
        <![CDATA[
            <p>Some text</p>
        ]]>
    </node2>
    <otherNodesHere>Yadda yadda</otherNodesHere>
</node>

The data being pulled from a data list is going to be "Some text" without the surrounding P tags.

So, what I'm wanting to do is (snippet):

new XElement("node",
    new XElement("node2",
        new XCData(
            new XElement("p", variableForTheDatainSP)),

But I can't do new XCData(new XElement("p", ....)), What would be a simple way to go about this?


Solution

  • The <p>Some text</p> isn't really an XElement - it's just text that looks like XML. So you'd use:

    new XElement("node",
        new XElement("node2",
            new XCData("<p>Some text</p>")))
    

    Or if you wanted to build it via an XElement, you could always call ToString():

    new XElement("node",
        new XElement("node2",
            new XCData(
                new XElement("p", variableForTheDatainSP).ToString()),