Search code examples
c#xmlxcdatamodel

Save XML file in C# without use XCData


I have a string like this on C#:

string sxml="<id>xpto</id>"

and I want to save an xml file using XLinq:

XElement cursosXML = new XElement("MenuItem", new XCData(sxml));
cursosXML.save("C:\\xpto.xml")

when I read my xml file this appears:

<MenuItem><![CDATA[<id>xpto</id>]]></MenuItem>

but I do not want <![CDATA[

How can I get this result?

<MenuItem>&lt;xpto&gt;3&lt;</MenuItem>

Solution

  • Here's how you should add the string to your element

            XElement sxml = XElement.Parse("<id>xpto</id>");
            XElement cursosXML = new XElement("MenuItem", sxml);
            cursosXML.Save("C:\\xpto.xml");
    



    Below Is an explanation of the troubles you've been having. It's just here for your reference

    <id>xpto</id> is an XML Element, but you're adding it to your current element as though it were a literal string. When you do this, the computer doesn't think you're adding a new child element to your main element, so it escapes it(explained later)

    The code I posted calls XElement.Parse(string), which will take your seralized xml string, and try to generate a valid XElement from it.


    What's happening is that &lt; is an escape sequence for < and &gt; is an escape sequence for >.

    the reason why your XML parser escapes < and > is because those characters have special meaning, and including them in your XML change the nature of XML.

    It's kinda similar to how \n is an escape sequence for the newline character, and how \\ is an escape sequence for \