2012-11-14 4 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

null가 나타납니다. 나는 애틀랜타 경찰을 얻고 싶은

(612) 목련 세인트 NW, 애틀랜타, GA 30314
404-658-6486 애틀랜타 경찰
398 센 테니얼 올림픽 공원 박사 NW, Atlanta, GA 30313
404-658-6636
Mithil

+1

r.Attribute ("section") 끝에 .Value를 추가하십시오. Attribute()는 결코 XAttribute를 반환하지 않습니다. == "string value" – 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, Atlanta, GA 30313 < Phone> 404-658-6636 < /Business> – Mithil

+0

@Mithil이 것이 작동합니다. –

+0

감사합니다 Kirill 내가 일하고있어. 질문을하거나 주석을 추가 할 때 xml 형식을 지정하는 방법을 모르겠습니다. – Mithil