更新时间:2023-11-05 16:59:52
按照@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);
输出与上面相同.