2011-12-20 111 views
1

我有以下XML文件:使用linq to xml查詢xml文件?

<?xml version="1.0" encoding="utf-8"?> 
<Cus> 
    <Customer Location="NJ"> 
    <Male Value="True" /> 
    <Name Value="xxx" /> 
    </Customer> 
    <Customer Location="NY"> 
    <Male Value="True" /> 
    <Name Value="yyy" /> 
    </Customer> 
</Cus> 

我想用LINQ to XML序得到男性的基於客戶位置的值進行查詢。

下面是該查詢:

var Male = from e in doc.Descendants("Male") 
      select new 
      { 
       Male = e.Attribute("Value").Value.ToString() 
      }; 

我能得到男性的價值,但我很困惑,如何基於客戶在XML file.How位置添加到得到名字這裏的條件決定了客戶的位置。如果有人能指導我,我將不勝感激。

回答

0

根據您的問題 - 選擇的基於位置的值,你可以使用類似:

private string CountOfMales(XDocument doc, string locationToFilter) 
{ 
    var selection = from customer in doc.Descendants("Customer") 
       .Where(c => c.Attribute("Location").Value == locationToFilter) 
       select new 
       { 
        MaleValue = customer.Element("Name").Attribute("Value").Value 
       }; 

       return selection.FirstOrDefault().MaleValue; 
} 
0

您希望在獲取男性之前在Customer元素上執行where子句。所以像這樣:

var males = from customer in doc.Descendants("Customer") 
      where "NY".Equals(customer.Attribute("Location").Value) 
      select customer.Descendants("Male"); 

注意:這尚未經過測試,但它應該給你一些指示如何進行。有關更多信息,請在where關鍵字上檢查此MSDN article

此外,如果它有幫助,我總是喜歡使用LINQ Extensions爲可枚舉集合。我發現它們比條款關鍵詞更容易閱讀和書寫。

0

這樣的事情我真的很喜歡這個XML擴展方法SafeElement和SafeAttribute因爲他們讓如果XML不包含您指定的元素或屬性,則可以查詢XML而不必擔心會出現空值。

這些擴展方法的代碼是在這裏:

public static XElement SafeElement(this XContainer container, string name) 
    { 
     return container.Element(name) ?? new XElement(name); 
    } 

    public static XAttribute SafeAttribute(this XElement element, string name) 
    { 
     return element.Attribute(name) ?? new XAttribute(name, ""); 
    } 

你使用這樣的:

 var customers = xdoc.Descendants("Customer") 
         .Where(x => x.SafeAttribute("Location").Value == "NJ") 
         .Select(x => x.SafeElement("Male").SafeAttribute("Value").Value); 

如果因任何原因的位置屬性或男性元素不存在你結束使用空結果集而不是例外。