-1

Question Background:

I have extracted the following inner XML from a larger document:

<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" /> 

Issue:

Using the following code, I have attempted to access each of the elements of the above XML. I need to extract both the name i.e 'total' and its value '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
 }

If someone can tell me how to get these values that would be great.

user1352057
  • 3,162
  • 9
  • 51
  • 117

3 Answers3

2

You're iterating though the ChildNodes collection of your element and since the element does not have any, you're iterating through the empty nodelist it gives you.

You want to iterate through the Attributes collection instead:

XmlAttributeCollection coll = element.Attributes;

for (int i = 0; i < coll.Count; i++)
{
    Console.WriteLine("name = " + coll[i].Name);
    Console.WriteLine("value = " + coll[i].Value);
}
Markus
  • 116
  • 4
1

It seems you need a Dictionary. Try using 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));
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

Managed to solve this myself:

 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;
      }
 };
user1352057
  • 3,162
  • 9
  • 51
  • 117