[英]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: 您可以执行以下几项操作:
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("'", "'").Replace("\\"", """).Replace(">", ">").Replace("<", "<").Replace("&", "&");
要解决此问题,请将特殊字符替换为转义的字符串格式
YourXmlString = YourXmlString.Replace("'", "'").Replace("\\"", """).Replace(">", ">").Replace("<", "<").Replace("&", "&");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.