views:

470

answers:

2

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>
A: 

Not tested and don't know if this is solution for you, but try replacing this

var origXml = "<Root><Item>Here is \"Some text&quot;</Item></Root>";

with this

var origXml = "<Root><Item>Here is \"Some text&amp;quot;</Item></Root>";
+1  A: 

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.

Jeff Yates