嗨,我有一个像下面的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>
我想获取服务名称=&#34; ReportWriter&#34;的配置键和值属性。
FOR ex-输出应为key1,value1,key2,value2为服务名称=&#39; ReportWriter&#39;。
任何人都可以帮我解决如何取悦
答案 0 :(得分: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();
答案 1 :(得分: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
来迭代它的元素并将其添加到现有字典中。
答案 2 :(得分:0)
Include