2015-08-17 25 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();