0

I get an error when deserializing a memorystream into a class if the "&" symbol appears in the xml text.

[XmlRoot(ElementName="DesEng")]
public class DesEng {
    [XmlAttribute(AttributeName="unit")]
    public string Unit { get; set; }
    [XmlText]
    public string Text{ get; set; }
}

var xmlSerializer = new XmlSerializer(typeof(T));
var temp = (T)xmlSerializer.Deserialize(ms); // error

The line on which the error appears.

<DesEng unit="per Sector">GSM/LTE Dual Mode license for Blade&AAU</DesEng>

Using XmlWriterSettings { CheckCharacters = false } result did not bring. I'm getting an error "There is an error in the XML document (229, 70)". If I change the & symbol to another, then deserialization in the class passes correctly.

Vlad Kisly
  • 354
  • 6
  • 16
  • That's invalid XML as the ampersand is the start symbol for an HTML entity. If you want to have an ampersand in your XML it needs to be escaped as &. The same applies for the < and > characters which need to be escaped as < and >. Whoever created the XML file needs to fix it. – ckuri Aug 17 '18 at 08:27
  • It should be either nnnn; or hhhh; See Wiki : https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references – jdweng Aug 17 '18 at 08:47
  • 1
    You have something that isn't valid XML and you can't change it? That's a bit like having a program that won't compile and which you can't change. It's junk, fit only for the trash. Send it back to whoever supplied it and tell them it's useless. – Michael Kay Aug 17 '18 at 11:17

2 Answers2

1

Try used the escaped form of the ampersand. You could replace it manually or you could replace it before you deserialise.

&amp;

For future reference, these characters also need to be escaped:

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

See the answer posted in this question: https://stackoverflow.com/a/1091953/2255454

avgcoder
  • 372
  • 1
  • 9
  • 27
  • I can not change the text of xml since it is accompanied by a checksum. – Vlad Kisly Aug 17 '18 at 08:44
  • @ВладимирК That's something you should mention in your question; I suggest editing it in – pinkfloydx33 Aug 17 '18 at 08:49
  • You can't replace it in memory as I suggested? Depends when it is checked but you can open the xml file, use file to read it into memory and then use the replace function to replace it, then deserialise. – avgcoder Aug 17 '18 at 08:59
  • Это ошибка формата xml файлов допущена вендором huawei. Их java софт не ругается. – Vlad Kisly Aug 31 '18 at 10:43
0

If you want to add "&" as a character in your xml. try used the escaped form of the ampersand.

Then your xml should be:

<DesEng unit="per Sector">GSM/LTE Dual Mode license for Blade&amp;AAU</DesEng>
Nhan Phan
  • 1,262
  • 1
  • 14
  • 32