0

Today I noticed XElement.Parse is not working for a case in my application and throwing an exception. Then turns out an invalid character (in this case &) was the cause. I had a line as follow in my xml string:

<label content="name1 & name2" startX="9" startY="69" >

I looked around the internet and could not find a good comprehensive solution because people mostly suggest to replace some special characters in the xml text before using XElement.Parsecommand.

Since I am not a XML expert and the content of the xml text is totally dynamic, what is the best solution in this case? By the way, I need to have the original text in my XElement object because it's going to be printed as a PDF file.

Mori
  • 2,484
  • 5
  • 28
  • 45
  • Yes, `XElement` is built to deal with XML, so if you hand it something that isn't valid XML, it's not surprising that it doesn't work. It's not so much that you should do some character replacements - you should fix whatever is generating this "xml" in the first place. – Damien_The_Unbeliever May 07 '15 at 10:15
  • Where's the XML coming from? Do you control it? As you've found, this isn't valid XML. Unless the source can be trusted to generate valid XML you're in for a long ride. I doubt `&` is the only invalid character. – Charles Mager May 07 '15 at 10:17
  • See following webpage : http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references – jdweng May 07 '15 at 10:17
  • The data is coming from the customer's side and we have no control over it. But I think this a relatively universal requirement and there has to be an API to to deal with! I can replace some special characters with other ones but who can predict the future and who is aware of the all possibilities?! – Mori May 07 '15 at 10:21
  • Well, This is what I did to avoid character replacement. I extracted the content from the text and used XmlConvert.EncodeName to encode the content. Then I parsed it with XElement.Parse and in the end before sending the text for printing, I used XmlConvert.DecodeName to have the original text. Could not find a better approach. – Mori May 07 '15 at 11:33

0 Answers0