2011-09-16 169 views
1

我知道這是一個簡單的問題,所以道歉,但我是新來的LINQ to XML,並因與以下困難:的LINQ to XML decendant元素

我有以下的XML,我試圖擺脫所有元素,包括地址要素:

<LawCentres> 
<LawCentre> 
    <LawCentreID>2</LawCentreID> 
    <LawCentreName>Test Law Centre</LawCentreName> 
    <Address> 
    <Address1>Test Address1</Address1> 
    <Address2>Test Address2</Address2> 
    <Address3>Test Address3</Address3> 
</Address> 
</LawCentre> 
<LawCentre> 
    <LawCentreID>22</LawCentreID> 
    <LawCentreName>Secondary Law Centre</LawCentreName> 
    <Address> 
    <Address1>ADDRESS11</Address1> 
    <Address2>ADDRESS21</Address2> 
    <Address3>ADDRESS31</Address3> 
    <CountryRef>10985</CountryRef> 
    <CountyRef>12116</CountyRef> 
    </Address> 
</LawCentre> 
</LawCentres> 

和我有下面的代碼寫的,但我有difficuty法律中心信息沿着提取地址: 的XDocument lawCentres = XDocument.Load(服務器.MapPath( 「XML \ LawCentres.xml」));

 var lawCentreQuery = from c in lawCentres.Descendants("LawCentre") 
          where (int)c.Element("LawCentreID") == lawCentreID 
          select new LawCentre 
          { 
           LawCentreName = (string)c.Element("LawCentreName"), 
           LawCentreID = (int)c.Element("LawCentreID"), 
           LawCentreAddressLine1 = (string)c.Element("Address1"), 
           LawCentreAddressLine2 = (string)c.Element("Address2"), 
           LawCentreAddressLine3 = (string)c.Element("Address3"), 
          }; 

任何想法?

回答

0

(string)c.Element("Address").Element("Address1")

OR

(string)c.Descendants("Address1").FirstOrDefault() 
+0

第二個選項可以完美取代(string)c.Element("Address1"),您的幫助哈桑萬分感謝! – Alicia

+0

@Alicia第一個選項有路徑錯誤;修復。現在,這也會起作用 –