Encode double quotes inside XML element using LINQ to XML
Posted
by davekaro
on Stack Overflow
See other posts from Stack Overflow
or by davekaro
Published on 2010-02-18T21:59:38Z
Indexed on
2010/03/27
0:53 UTC
Read the original article
Hit count: 711
I'm parsing a string of XML into an XDocument that looks like this (using XDocument.Parse)
<Root>
<Item>Here is "Some text"</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 "Some text"</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 "
and not \"
?
UPDATE: Maybe this can explain it better:
var origXml = "<Root><Item>Here is \"Some text"</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"</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>
I want the output to be:
<Root><Item>Here is "Some text"</Item></Root>
<Root><Item>Here is "Some text"</Item></Root>
© Stack Overflow or respective owner