在 xml 中按父节点获取子节点属性

Get Child node attribute by parent in 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"。

FOR ex- 输出应该是 key1, value1, key2, value2 for service name= 'ReportWriter'.

任何人都可以帮助我如何实现

您可以使用 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();

试试这个:-

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

更新:

上面的查询 returns a Dictionary<string,string>,您可以使用 a foreach 遍历它的元素并将其添加到现有字典中。

        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();