Search code examples
c#.netxmllinq-to-xmlxelement

How to add child element to XElement as a decoded string?


I want to make pass this test. What should I use instead of Add method?

[TestMethod]
public void AddContentWithoutEncoding()
{
   var element = new XElement("Parent");

   element.Add("<Son>5</Son>");

   Assert.IsTrue(element.ToString() == "<Parent><Son>5</Son></Parent>");
}

With the current approach element.ToString() = "<Parent>&lt;Son&gt;5&lt;/Son&gt;</Parent>" that's obviously encoding tag content.

I have a big constant string with tags which I need to add to XElement (because I use it feurther). And want to use some clever solution than HttpUtility.HtmlDecode - just add the decoded string rather than decode the whole result after adding.

Thanks!


Solution

  • Try,

    var element = new XElement("Parent");
    foreach(string xml in list)
        element.Add(XElement.Parse(xml));
    

    You probably also want in your Assert...

    Assert.IsTrue(element.ToString(SaveOptions.DisableFormatting) == ...