0

Using XmlDocument.LoadXml(), how can I load a string with & or < in it?

For instance, the following string causes an error:

<choice id="A1"> sample < text</choice>

Do I need to use a Resolver somehow? Can XmlDocument even handle things like this?

Matheus Cuba
  • 2,068
  • 1
  • 20
  • 31
dyerme
  • 1
  • What error you get? Compilation error or runtime error? Post the details of the error. – Sriram Sakthivel Apr 17 '18 at 16:36
  • 3
    Well, that's not valid XML, so XmlDocument won't load it. It should be ` sample < text`. Where is the XML coming from? – stuartd Apr 17 '18 at 16:42
  • @SriramSakthivel It was a run-time error due to the data -- "Illegal character". – dyerme Apr 17 '18 at 17:41
  • @stuartd You're right: I was letting the XML supplier perform an "entity expand" on the string. When I changed that, it loads and displays fine. Thanks! – dyerme Apr 17 '18 at 17:43
  • @stuartd Now no other entities work, only "&" and "<" work. The run-time error is "Reference to undeclared entity 'dagger'" (e.g.). Ampersand and Less Than seem to be special and require unique treatment. How do I reference entities; is this where a Resolver comes into play? – dyerme Apr 17 '18 at 17:48
  • See wiki to handle special characters : https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references – jdweng Apr 17 '18 at 18:14
  • *How do I reference entities; is this where a Resolver comes into play?* -- can you provide a sample of XML that cannot be parsed? – dbc Apr 17 '18 at 19:13
  • @dbc In this example, "¶" can't be resolved: choice ¶&< 1 – dyerme Apr 17 '18 at 19:26
  • Well that's also malformed XML, upload it to https://www.xmlvalidation.com/ and you will see **Errors in the XML document: The entity "para" was referenced, but not declared.** But `&para` is predefined in HTML, are you sure you shouldn't be parsing it as HTML as suggested in [Reference to undeclared entity exception while working with XML](https://stackoverflow.com/a/281703) instead? – dbc Apr 17 '18 at 19:38
  • @dbc I'm definitely using XML versus HTML (although obviously I'm new at it). Also, this is a string fragment that I want to load into an XmlDocument. I've learned there is an entity file available to the system, but my attempt to leverage it via XmlUrlResolver.ResolverUri() was unsuccessful; I'm still getting "Reference to undeclared entity". How do I reference these entities -- either W3C's or something on the local system? – dyerme Apr 17 '18 at 20:07
  • @dbc Actually it did work -- it looks like using an XmlUrlResolver is the way to go. Thanks for your input! – dyerme Apr 17 '18 at 20:10

0 Answers0