简体   繁体   English

解析带有“&”的实体名称时发生错误

[英]an error occurred while parsing entityname with '&'

I have the next program that open a .XML document with Visual c#. 我有下一个使用Visual c#打开.XML文档的程序。 I can´t open the Xml because it has a '&', and I don´t know how i can open. 我无法打开Xml,因为它带有'&',而且我不知道该如何打开。

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. 那么XML元素名称中的某个位置会有一个“&”。 This is not allowed in an XML document. XML文档中不允许这样做。 You cannot open an invalid XML file with the XmlDocument (or XDocument ) class. 您不能使用XmlDocument (或XDocument )类打开无效的XML文件。

There are several things you can do: 您可以执行以下几项操作:

  1. Make sure that the XML files are always valid before trying to read them. 尝试读取XML文件之前,请确保它们始终有效。 This however depends on your scenario and may not be possible. 但是,这取决于您的情况,可能无法实现。
  2. Preprocess your XML file to fix the invalid content by replacing "&" with "&". 通过将“&”替换为“&”来预处理XML文件以修复无效的内容。 You can either do this manually or at run-time. 您可以手动执行此操作,也可以在运行时执行。
  3. Use HtmlAgilityPack to parse the invalid file. 使用HtmlAgilityPack解析无效的文件。

Personally, I would go with 1) if possible or 2) otherwise. 就个人而言,我将尽可能选择1)或2)。

Replace all occurances of & with & &所有出现替换为& in the xml. 在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. 因此,在花了几个小时解决这个问题之后:事实证明,如果您在xml字符串中包含一个&符号或其他XML转义字符,则在尝试读取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;"); 要解决此问题,请将特殊字符替换为转义的字符串格式YourXmlString = YourXmlString.Replace("'", "&apos;").Replace("\\"", "&quot;").Replace(">", "&gt;").Replace("<", "&lt;").Replace("&", "&amp;");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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