Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving a string's Xml encoded characters

Tags:

c#

linq-to-xml

I need to update an XML document; using C# and preferably Linq To Xml. The source XML file has the following node:

<characters>Lorem &#xD;Ipsum</characters>

I need to update this node to something like this:

<characters>Lorem1 &#xD;Ipsum2</characters>

When I read in the string from the Xml; I get this:

"Lorem &#xD;Ipsum"

and when I write the string using

copyEl.SetElementValue(ns + "characters", "Lorem1 &#xD;Ipsum2");

the outputted Xml has the leading ampersand of the encoded character being re-escaped:

 <characters>Lorem1 &amp;#xD;Ipsum2</characters>

I want to preserve the Xml encoding in the original string as is; but am unsure as to how to do it. Any thoughts?

like image 315
Frank Rosario Avatar asked Jan 31 '26 03:01

Frank Rosario


1 Answers

The beauty of using Linq-to-XML, or any xml abstraction class for that matter, is that you don't need to worry about string encoding. Just pass in the string as a C# string, and let linq convert it to an XML string for you:

copyEl.SetElementValue(ns + "characters", "Lorem1 \rIpsum2");
like image 163
gilly3 Avatar answered Feb 02 '26 18:02

gilly3



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!