Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode double quotes inside XML element using LINQ to XML

I'm parsing a string of XML into an XDocument that looks like this (using XDocument.Parse)

<Root>
  <Item>Here is &quot;Some text&quot;</Item>
</Root>

Then I manipulate the XML a bit, and I want to send it back out as a string, just like it came in

<Root>
  <Item>Here is &quot;Some text&quot;</Item>
  <NewItem>Another item</NewItem>
</Root>

However, what I am getting is

<Root>
  <Item>Here is \"Some text\"</Item>
  <NewItem>Another item</NewItem>
</Root>

Notice how the double quotes are now escaped instead of encoded?

This happens whether I use

ToString(SaveOptions.DisableFormatting);

or

var stringWriter = new System.IO.StringWriter();
xDoc.Save(stringWriter, SaveOptions.DisableFormatting);
var newXml = stringWriter.GetStringBuilder().ToString();

How can I have the double quotes come out as &quot; and not \"?

UPDATE: Maybe this can explain it better:

var origXml = "<Root><Item>Here is \"Some text&quot;</Item></Root>";
Console.WriteLine(origXml);
var xmlDoc = System.Xml.Linq.XDocument.Parse(origXml);
var modifiedXml = xmlDoc.ToString(System.Xml.Linq.SaveOptions.DisableFormatting);
Console.WriteLine(modifiedXml);

the output I get from this is:

<Root><Item>Here is "Some text&quot;</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>

I want the output to be:

<Root><Item>Here is "Some text&quot;</Item></Root>
<Root><Item>Here is "Some text&quot;</Item></Root>
like image 535
davekaro Avatar asked Nov 05 '22 16:11

davekaro


1 Answers

You should use an XmlWriter to ensure characters are encoded correctly. However, I'm not sure that you can get the exact output you want without rolling your own class to output the text.

like image 91
Jeff Yates Avatar answered Nov 13 '22 17:11

Jeff Yates