LINQ to xml - 如何选择特定节点?

时间:2012-11-14 00:07:16

标签: c# .net xml linq xpath

我有这个xml。如何根据“部分”选择<region>

<PhoneAndAddresses>
  <PageTitle></PageTitle>
  <region section="CityServices">
    <Business>
      <Name>
        Atlanta Police Department
        <Name>
          <Address>612 Magnolia St NW, Atlanta, GA 30314</Address>
          <Phone>404-658-6486</Phone>
        </Business>
    <Business>
      <Name>Atlanta Police Department</Name>
      <Address>398 Centennial Olympic Park Dr NW, Atlanta, GA 30313</Address>
      <Phone>404-658-6636</Phone>
    </Business>
  </region>
  <region section="Hospitals">
    <Business>
      <Name>
        Emory University Hospital
        <Name>
          <Address>612 Magnolia St NW, Atlanta, GA 30314</Address>
          <Phone>404-658-6486</Phone>
        </Business>
    <Business>
      <Name>
        St Joseph's Hospital
        <Name>
          <Address>398 Centennial Olympic Park Dr NW, Atlanta, GA 30313</Address>
          <Phone>404-658-6636</Phone>
        </Business>
  </region>
</PhoneAndAddresses>

2 个答案:

答案 0 :(得分:2)

使用:

var result = XDocument.Parse(input).Descendants("region")
    .FirstOrDefault(e => (string)e.Attribute("section") == "CityServices");

或使用XPath:

//region[@section = 'CityServices']

答案 1 :(得分:2)

尝试这样的事情(未经测试):

var doc = XDocument.Parse(xmltext);
var selectedRegion = doc.Root.Descendents("region").FirstOrDefault(r => r.Attribute("section").Value == "target value");