2014-01-16 37 views
1

我有一個XML文件的LINQ to XML ...零和缺失的元素

<Person> 
<PersonItem id="0"> 
    <Time>1/8/2014</Time> 
    <Step><![CDATA[Normal]]></Step> 
    <HasAddress/> 
    <Address/> 
</PersonItem> 
<PersonItem id="1"> 
    <Time>1/8/2014 3:21:45 PM</Time> 
    <Step><![CDATA[Normal]]></Step> 
    <HasAddress/> 
    <Address/> 
</PersonItem> 
<PersonItem id="2"> 
    <Time>1/8/2014</Time> 
    <Step><![CDATA[Normal]]></Step> 
    <HasAddress>Main</HasAddress> 
    <Address> 
     <AddressItem id="0" location=5> 
      <Address>15 Oak</Address> 
     </AddressItem> 
     <AddressItem id="1" location=7> 
      <Address>12 Maple</Address> 
     </AddressItem> 
     <AddressItem id="2" location=8> 
      <Address>30 Beech</Picture> 
     </AddressItem> 
    </Address> 
</PersonItem> 
</Person> 

我希望把檢索信息併發送一些它的數據庫。我嘗試了幾種不同的方法來處理這個問題,我相信我很接近。這是我嘗試過的Linq。

public void DoIt(fileName) 
{ 
    XElement xml = XElement.Load(fileName); 

    var items = from item in xml.Elements("PersonItem") 
       where (from x in item.Elements("HasAddress") 
         where x.Element("HasAddress") != null 
         select x).Any() 
       select item; 

    Array.ForEach(items.ToArray(), 
     o=>Console.WriteLine(o.Element("Time").Value)); 
    Console.ReadLine(); 
} 

問題是沒有被返回。

回答

0

試試這個:

XElement xml = XElement.Load(fileName); 
var items = xml.Descendants("PersonItem") 
       .Where(x => (string)x.Element("HasAddress") != null) 
       .Select(x => x); 
+0

我沒有得到任何數據恢復「枚舉沒有結果」 – sjr

0
XDocument xml = XDocument.Load("Input.xml"); 

var items = from item in xml.Root.Elements("PersonItem") 
      where !string.IsNullOrEmpty((string)item.Element("HasAddress")) 
      select item; 

對於您的示例XML文檔返回只有最後PersonItem元素。

+0

我怎麼會看到所有的元素和PersonItem id和AddressItem ID最後PersonItem元素如「時間」和「地址」 – sjr

+0

您可以在返回的'item'上執行另一個查詢,它是'IEnumerable '與所有匹配的'PersonItem'元素。 – MarcinJuraszek

+0

項的值爲「枚舉沒有結果」,所以沒有什麼可查詢的 – sjr

1

可能只是一個錯字,但在您的xml文件中存在此標記錯誤。

<Address>30 Beech</Picture> 

這應該是:

<Address>30 Beech</Address> 
+0

對不起,只是一個錯字 – sjr

+0

隨着錯字的修復,我可以使用@ MarcinJuraszek的代碼沒有xml.Root.Elements,只是xml.Elements,我得到結果我認爲你正在尋找。 – Kohins

+0

我也使用你的XElement xml = XElement.Load(fileName)加載;他的不安。 – Kohins