2

I have this xml data

<Categories>
    <cat name="Appliances"></cat>
    <cat name="Arts, Crafts & Sewing"></cat>
    <cat name="Automotive"></cat>
    <cat name="Baby"></cat>
</Categories>

and I use this code to read the data into combobox:

XmlDocument xDoc = new XmlDocument();
xDoc.Load("cat.xml");
XmlNodeList cats = xDoc.GetElementsByTagName("cat");
for (int i = 0; i < cats.Count; i++)
{
   comboBox1.Items.Add(cats[i].Attributes["name"].InnerText);
}

but at line xDoc.Load("cat.xml"); I get error:

An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll An error occurred while parsing EntityName. Line 3, position 30.

what this mean ?

zac
  • 4,495
  • 15
  • 62
  • 127
  • 1
    Take a look in [this question here](http://stackoverflow.com/questions/23541910/an-error-occurred-while-parsing-entityname-line1-position-844) and tell me if it helps you. – Alisson Reinaldo Silva May 21 '17 at 22:05

1 Answers1

3

Your xml contains an ampersand that makes it invalid, try this before parsing

var xmlContent = File.ReadAllText("cat.xml");
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xmlContent.Replace("&", "&amp;"));
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • I tried `xDoc.LoadXml(SecurityElement.Escape(xmlContent));` but I get now error Data at the root level is invalid. Line 1, position 1. – zac May 21 '17 at 22:37
  • 2
    @Wel you cann't use `SecurityElement.Escape` here (it is wrong edit from @Alisson. I'm going to remove it) because it will replace even `<` and `>` but you need to replace only ampersand. Use `xmlContent.Replace("&", "&")` – Roman Marusyk May 21 '17 at 22:55