无法访问内部Xml元素

时间:2014-05-20 15:12:34

标签: c# xml xmldocument

问题背景:

我从更大的文档中提取了以下内部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的每个元素。我需要提取两个名称,即&#39; total&#39;及其价值&#39; 1&#39;;

 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
 }

如果有人可以告诉我如何获得这些值很高的价值。

3 个答案:

答案 0 :(得分:2)

您正在通过元素的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);
}

答案 1 :(得分:1)

您似乎需要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));

答案 2 :(得分:0)

管理自己解决这个问题:

 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;
      }
 };
相关问题