簡體   English   中英

使用linq到xml查詢xml文件?

[英]Query an xml file using 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到xml進行查詢,以便根據客戶位置獲取男性的價值。

這是查詢:

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

我能夠獲得男性的價值,但我很困惑如何根據xml文件中客戶的位置獲取名稱。如何在此處添加確定客戶位置的條件。如果有人可以指導我。

您想要在獲取男性之前對Customer元素執行where子句。 所以像這樣:

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

注意:此操作尚未經過測試,但應為您提供一些有關如何進行操作的指示。 where關鍵字上查看此MSDN文章 ,以了解更多信息。

另外,如果有幫助,我總是喜歡將LINQ擴展用於可枚舉的集合。 我發現它們比子句關鍵字更容易讀寫。

根據您的問題-要根據位置選擇name的值,可以使用類似以下內容的方法:

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;
}

對於這樣的事情,我真的很喜歡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);

如果由於某種原因不顯示Location屬性或Male元素,則結果將為空,而不是異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM