简体   繁体   中英

an error occurred while parsing entityname with '&'

I have the next program that open a .XML document with Visual c#. I can´t open the Xml because it has a '&', and I don´t know how i can open.

private void button1_Click(object sender, EventArgs e)
{
    XmlDocument doc;
    doc = new XmlDocument();
    doc.Load("nuevo.xml");

    XmlNodeList menus;
    menus = doc.GetElementsByTagName("menu");

    foreach (XmlNode unMenu in menus)
    {
        if (unMenu.Attributes["precio"].Value == "50")
        {
            //Console.WriteLine(unMenu.Attributes["type"].Value);
            XPathNavigator navegador = doc.CreateNavigator();
            XPathNodeIterator nodos = navegador.Select("/restaurante");
            while (nodos.MoveNext())
            {
                Console.WriteLine(nodos.Current.OuterXml);
                Console.WriteLine();
                textBox1.Text = nodos.Current.OuterXml;
            }
        }    
    }
}

If you get the error

an error occurred while parsing entityname with '&'

then there is an "&" somewhere in the name of an XML element. This is not allowed in an XML document. You cannot open an invalid XML file with the XmlDocument (or XDocument ) class.

There are several things you can do:

  1. Make sure that the XML files are always valid before trying to read them. This however depends on your scenario and may not be possible.
  2. Preprocess your XML file to fix the invalid content by replacing "&" with "&". You can either do this manually or at run-time.
  3. Use HtmlAgilityPack to parse the invalid file.

Personally, I would go with 1) if possible or 2) otherwise.

Replace all occurances of & with & in the xml.

So after spending hours on this issue: it turns out that if you have an ampersand symbol ("&") or any other XML escape characters within your xml string, it will always fail will you try read the XML. TO solve this, replace the special characters with their escaped string format YourXmlString = YourXmlString.Replace("'", "&apos;").Replace("\\"", "&quot;").Replace(">", "&gt;").Replace("<", "&lt;").Replace("&", "&amp;");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM