Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 578
Dmitry Khryukin Avatar asked Dec 16 '22 21:12

Dmitry Khryukin


2 Answers

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) == ...
like image 54
Chuck Savage Avatar answered Dec 18 '22 10:12

Chuck Savage


You can do an XElement.Parse and then add like this:

var element = new XElement("Parent");

element.Add(XElement.Parse("<Sone>5</Sone>"));

Console.WriteLine(element.ToString(SaveOptions.DisableFormatting));

This gives me the output you are looking for.

like image 45
Davin Tryon Avatar answered Dec 18 '22 11:12

Davin Tryon