linq基于多个子元素从xml中选择父元素

时间:2015-10-11 17:46:29

标签: c# xml linq c#-4.0

如何选择<client>元素,其中<domain>包含任何指定值:

 <config>
  <client>
    <name>Localhost</name>
    <domains>
      <domain>localhost</domain>
      <domain>192.168.43.12</domain>
    </domains>
    <moduletype>t</moduletype>
    <contactname>Home Manager</contactname>
    <contactemail>a@a.com</contactemail>
    <contactphone1>+133255111</contactphone1>
    <contactphone2>+1332552</contactphone2>
  </client>
  <client>
    <name>Client A</name>
    <domains>
      <domain>a.com</domain>
      <domain>c.com</domain>
      <domain>d.com</domain>
    </domains>
    <moduletype>t</moduletype>
    <contactname>Client A</contactname>
    <contactemail>info@c.com</contactemail>
    <contactphone1>+12553254</contactphone1>
    <contactphone2>+14403253</contactphone2>
  </client>
</config>

例如:if&#34; 192.168.43.12&#34;域名被传递,它应该选择客户端Localhost,如果&#34; c.com&#34;域名被传递,它应该选择客户端客户端A

我试过了:

string domain_name = "192.168.43.12";

XElement record = xmldoc.Element("config").Elements("client").Elements("domains").Where(x => (string)x.Element("domain") == domain_name).SingleOrDefault();

但是它会产生null结果;

1 个答案:

答案 0 :(得分:2)

您可以使用此类查询:

XElement record = xmldoc.Element("config")
    // from all client elements
    .Elements("client")    
    // filter the one that has child element <domain> with value domain_name
    .Where(x=>x.Descendants("domain").Any(v=>v.Value == domain_name))
    // select only one or default
    .SingleOrDefault();