无法读取包含&符号的XML文档 [英] Can not read XML document containing ampersand symbol
问题描述
我正在编写一个使用Visual C#读取XML文件的程序.我在读取Xml文件时遇到问题,因为它包含无效的XML符号,例如'&'.
I am writing a program that reads a XML file with Visual C#. I have a problem reading the Xml file, because it contains invalid XML symbols, for example '&'.
我必须阅读XML,但无法修改文档.如何使用C#修改Xml文件?到目前为止,我的代码:
I have to read the XML but I can not modify the document. How can I modify the Xml file using C#? My code so far:
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc;
doc = new XmlDocument();
doc.Load("nuevo.xml");
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
textBox1.Text = nodo.InnerXml;
}
推荐答案
按照@EBrown的建议,一种可能性是读取字符串变量中的文件内容,并用正确的&
符号替换表示XML &
,然后解析XML结构.可能的解决方案如下所示:
As @EBrown suggested, one possibility would be read the file content in a string variable and replace the &
symbol with the correct representation for propert XML &
and then parse the XML structure. A possible solution could look like this:
var xmlContent = File.ReadAllText(@"nuevo.xml");
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(xmlContent.Replace("&", "&"));
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
Console.WriteLine(nodo.InnerXml.Replace("&", "&"));
}
输出为:
34 & 34
如果可以使用LINQ2XML,则解决方案甚至更短,并且无需编写反向(第二)替换,因为LINQ2XML会自动为您做到这一点:
If it is ok to use LINQ2XML, then the solution is even shorter, and there is no need to write the reverse(second) replace, because LINQ2XML make this for you automatically:
var xmlContent = File.ReadAllText(@"nuevo.xml");
var xmlDocument = XDocument.Parse(xmlContent.Replace("&", "&"));
var edad = xmlDocument.Root.Element("edad").Value;
Console.WriteLine(edad);
输出与上面相同.
这篇关于无法读取包含&符号的XML文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!