2011-12-20 109 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); 

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