4

I have an XML that contains attribute strings containing escaped characters such as <.

After reading such a file with XDocument and accessing the attribute content using .Value, all such escaped characters get decoded. .Value will return a string containing <, not &lt;.

Is there a way of keeping the raw text contained in the XML strings, not decoding them?

Rok Povsic
  • 4,626
  • 5
  • 37
  • 53
  • If xml strings doesn't contains both, escaped `<` and unescaped `<`, then you can simply read attribute value as you do and escape it. It seems there is [`InnerXml` property](https://stackoverflow.com/a/1132533/1997232), perhaps you can just use `XmlDocument`? – Sinatr Oct 12 '17 at 13:43
  • You can escape it using something like `new XText(x.Value).ToString()`, though there's no guarantee the result will be identical to the source. – Charles Mager Oct 12 '17 at 13:48
  • I've spent quite some time once trying to do that (right as you describe - avoid expanding all xml entities including character entities), without any success. – Evk Oct 12 '17 at 14:05
  • I don't think there is any way to do this with `XDocument`. There is some ability to do this with the old `XmlDocument` and `XmlTextReader` however, see [How do you keep .NET XML parsers from expanding parameter entities in XML?](https://stackoverflow.com/q/30598841) and [Entity References are Expanded and Not Preserved](https://learn.microsoft.com/en-us/dotnet/standard/data/xml/entity-references-are-expanded-and-not-preserved). – dbc Oct 12 '17 at 14:40

1 Answers1

-2

It is not very beautiful, but I use this:

var attributeText = attribute.ToString();
attributeText = attributeText.TrimPrefix(attributeName);
attributeText = attributeText.TrimStart('=');
attributeText = attributeText.Trim('\"');
Fabian
  • 1,100
  • 11
  • 14