无法访问内部Xml元素

本文关键字:Xml 元素 内部 访问 | 更新日期: 2023-09-27 18:04:28

问题背景:

我从一个较大的文档中提取了以下内部XML:

<Counters total="1" executed="1" passed="1" error="0" failed="0" timeout="0" aborted="0" inconclusive="0" passedButRunAborted="0" notRunnable="0" notExecuted="0" disconnected="0" warning="0" completed="0" inProgress="0" pending="0" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010" /> 

问题:

使用以下代码,我尝试访问上述XML的每个元素。我需要提取名称,即"total"及其值"1";

 XmlDocument innerXmlDoc = new XmlDocument();
 innerXmlDoc.LoadXml(node.InnerXml);
 XmlElement element = innerXmlDoc.DocumentElement;
 XmlNodeList elements = element.ChildNodes;
 for (int i = 0; i < elements.Count; i++)
 {
     //logic
 }

如果有人能告诉我如何获得这些价值观,那就太好了。

无法访问内部Xml元素

您正在遍历元素的ChildNodes集合,由于该元素没有,因此您正在遍历它提供的空节点列表。

您希望遍历Attributes集合:

XmlAttributeCollection coll = element.Attributes;
for (int i = 0; i < coll.Count; i++)
{
    Console.WriteLine("name = " + coll[i].Name);
    Console.WriteLine("value = " + coll[i].Value);
}

您似乎需要一个Dictionary。尝试使用LINQ to XML

var values = new Dictionary<string,string>();
var xmlDocument = XDocument.Load(path);
XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
values = xmlDocument
        .Descendants(ns + "Counters")
        .SelectMany(x => x.Attributes)
        .ToDictionary(x => x.Name, x => (string)x));

我自己设法解决了这个问题:

 foreach (XmlNode node in nodes) 
 {
      XmlDocument innerXmlDoc = new XmlDocument();
      innerXmlDoc.LoadXml(node.InnerXml);
      var list  = innerXmlDoc.GetElementsByTagName("Counters");
      for (int i = 0; i < list.Count; i++)
      {
         string val = list[i].Attributes["total"].Value;
      }
 };