Can’t read XML document if contains ampersand symbol

Problem:

System.Xml.XmlException: An error occurred while parsing EntityName.


Description:

I had the following C# code snippet and got error on the line 6 at doc.Load(…):

System.Xml.XmlException: An error occurred while parsing EntityName. Line 4, position 18.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
private void LoadXML()
{
     try
     {
          XmlDocument doc = new XmlDocument();
          doc.Load("data.xml");

          //...
     }
     catch (Exception ex)
     {
          string msg = ex.ToString();
     }
}

I checked the XML document and on the line 4 and position 18 I had & (ampersand) sign.

<?xml version="1.0" standalone="yes"?>
<Items>
  <Item>
    <Text>Black & White</Text>
  </Item>
</Items>

So the question is: how to parse XML file with & (ampersand) sign? 🙂

Solution:

Then I replaced the ampersand sign in the XML document with the appropriate escape sequences: &amp; and the problem was solved.

Here is the modified XML document:

<?xml version="1.0" standalone="yes"?>
<Items>
  <Item>
    <Text>Black &amp; White</Text>
  </Item>
</Items>

6x faster WordPress Hosting6x faster WordPress Hosting