Encoding double quotes inside an XML element using LINQ to XML

I am parsing an XML string in 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 as a string, just like in

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

However, I get

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

Notice how double quotes are now escaped rather than encoded?

This happens if 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 get double quotes like &quot; , but not \" ?

UPDATE Perhaps this may 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> 
+4
source share
2 answers

You must use XmlWriter to ensure that character encoding is correct. However, I'm not sure that you can get the exact result you want without folding your own class to output text.

+2
source

Not tested and don't know if this solution is 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>"; 
0
source

Source: https://habr.com/ru/post/1301750/


All Articles