2015-08-17 77 views
-2

嗨,我有一個如下所示的xml。通過xml中的父級獲取子節點屬性

<Services> 
     <Service Name="ReportWriter" AssemplyName="ReportService.ReportWriters" ClassName="ExcelWriter"> 
     <ServiceConfigurations> 
     <Configuration key="key1" value="value1" /> 
<Configuration key="key2" value="value2" /> 

     </ServiceConfigurations> 
     </Service> 
     <Service Name="LogtWriter" AssemplyName="" ClassName=""> 
     <ServiceConfigurations> 
      <Configuration key="" value="" /> 
     </ServiceConfigurations> 
     </Service> 
     <Service Name="OutputHandler" AssemplyName="" ClassName=""> 
     <ServiceConfigurations> 
      <Configuration key="key1" value="value1" /> 
<Configuration key="key2" value="value2" /> 
     </ServiceConfigurations> 
     </Service> 
</Services> 

我想獲取服務名=「ReportWriter」的配置鍵和值屬性。

對於ex-output,應該是服務名稱='ReportWriter'的key1,value1,key2,value2。

任何人可以幫助我如何才達到請

回答

0

試試這個: -

Dictionary<string,string> result = xdoc.Descendants("Service") 
        .First(x => (string)x.Attribute("Name") == "ReportWriter") 
        .Descendants("Configuration") 
        .Select(x => new 
          { 
           Key = x.Attribute("key").Value, 
           Value = x.Attribute("value").Value 
          }).ToDictionary(x => x.Key, y => y.Value) ; 

更新:

上面的查詢返回Dictionary<string,string>,您可以使用foreach通過它的元素進行迭代,並把它添加到您現有的字典。

+0

嗨拉胡爾。這很好,謝謝。如果我想將鍵和值添加到字典類型的對象中。那麼應該是什麼代碼 –

+0

@ sandeep.mishra - 請檢查我的更新。 –

1

您可以使用Linq2Xml和XPath

var xDoc = XDocument.Load(filename); 
var conf = xDoc.XPathSelectElements("//Service[@Name='ReportWriter']/ServiceConfigurations/Configuration") 
      .Select(c => new { Key = (string)c.Attribute("key"), Value = (string)c.Attribute("value") }) 
      .ToList(); 

或者沒有的XPath

var conf = xDoc.Descendants("Service") 
       .First(srv => srv.Attribute("Name").Value == "ReportWriter") 
       .Descendants("Configuration") 
       .Select(c => new { Key = (string)c.Attribute("key"), Value = (string)c.Attribute("value") }) 
       .ToList(); 
0
 var doc = XDocument.Load(filepath); 
     var result = doc 
      .Descendants("Service")    
      .Where(x => x.Attribute("Name").Value == "ReportWriter") 
      .Descendants("Configuration") 
      .Select(x => new 
      { 
       Key = x.Attribute("key").Value, 
       Value = x.Attribute("value").Value 
      }).FirstOrDefault();