2014-05-20 88 views
-1

問題背景:無法訪問內的XML元素

我已經從一個較大的文檔中提取的以下內部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 
} 

如果有人能告訴我如何獲得這些值將是偉大的。

+1

嗨。你想訪問節點元素還是單個元素計數器的屬性? – Ksv3n

+2

自閉標籤沒有任何子節點。它確實有屬性。 – CoderDennis

+0

@Ksven非常感謝您的幫助。發佈這個問題後我很快解決了這個問題。 – user1352057

回答

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; 
     } 
}; 
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

你迭代雖然你的元素的childNodes集合和由於元件沒有任何,你通過空迭代nodelist它給你。

你想通過屬性集合而不是遍歷:

XmlAttributeCollection coll = element.Attributes; 

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