2012-11-14 61 views
1

我有這個xml。如何根據「部分」選擇<region>LINQ to xml - 如何選擇特定的節點?

<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

嘗試是這樣的(未經測試):

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

我得到空。我想 亞特蘭大警察局

612木蘭街NW,亞特蘭大,GA 30314
404-658-6486 亞特蘭大警察局
398百年奧林匹克公園博士NW,Atlanta,GA 30313
404-658-6636
Mithil

+1

將值添加到r.Attribute(「section」)的末尾。 Attribute()返回一個XAttribute,它永遠不會==「字符串值」 – dthorpe

+0

這樣做。非常感謝@dthorpe – Mithil

2

用途:

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

或使用XPath:

//region[@section = 'CityServices'] 
+0

我得到空。我想 < Name>亞特蘭大警察局 < Address> 612木蘭街NW,亞特蘭大,GA 30314 < Phone> 404-658-6486 < /Business> < Business> < Name>亞特蘭大警察局 < Address> 398百年奧林匹克公園NW博士,亞特蘭大,GA 30313 < Phone> 404-658-6636 < /Business> – Mithil

+0

@Mithil,這應該有效。 –

+0

感謝基里爾我得到了它的工作。我不確定如何在提問或添加評論時格式化xml。 – Mithil