簡體   English   中英

多個相同元素上的LINQ-To-XML查詢

[英]LINQ-To-XML Query on Mulitple Identical Elements

我對LINQ和XML相當陌生,正在嘗試使用現有的500k行XML文件,該文件的結構與下面的XML相同。 我已經找到了如何測試多個空XElement的方法,但完全陷入了如何搜索多個相同XElement的問題。

我如何讓LINQ只返回適用於Google的聯系人?

謝謝大家。

void Main()
{
XDocument AddressBook = CreateAddressBookXML();

var query =
        from contact in AddressBook.Descendants("Contact")
        let companyelement = contact.Element("Company") 
        where companyelement != null
        let companyname    = companyelement.Descendants("CompanyName")
        where companyname != null && companyname == "Google"
        select contact;


Console.Write(query);

}


public XDocument CreateAddressBookXML() {
    XDocument result =
      new XDocument(
        new XComment("My phone book"),
        new XElement("phoneBook",
          new XComment("My friends"),
          new XElement("Contact",
            new XAttribute("name", "Ralph"),
            new XElement("homephone", "555-234-4567"),
            new XElement("cellphone", "555-345-75656"),
            new XElement("Company",
                new XElement("CompanyName","Ralphs Web Design"),
                new XElement("CompanyName","Google")
            )
        ),
          new XElement("Contact",
            new XAttribute("name", "Dave"),
            new XElement("homephone", "555-756-9454"),
            new XElement("cellphone", "555-762-1546"),
            new XElement("Company",
                new XElement("CompanyName","Google")
            )
        ),
          new XComment("My family"),
          new XElement("Contact",
            new XAttribute("name", "Julia"),
            new XElement("homephone", "555-578-1053"),
            new XElement("cellphone", "")
        ),
          new XComment("My team"),
          new XElement("Contact",
            new XAttribute("name", "Robert"),
            new XElement("homephone", "555-565-1653"),
            new XElement("cellphone", "555-456-2567"),
            new XElement("Company",
                new XElement("CompanyName","Yahoo")
                )
        )
    )
  );

    return result;
}
var query = from contacts in CreateAddressBookXML().Root.Descendants("Contact")
            where contacts.Element("Company") != null &&
                  contacts.Element("Company").Elements("CompanyName").
            FirstOrDefault(c => c.Value == "Google") != null
            select contacts;

我通常更喜歡混用XPath來編寫這些查詢,它比LINQ等效文件緊湊得多。

var query =
    from contact in doc.XPathSelectElements("/phoneBook/Contact")
    where contact.XPathSelectElements("Company/CompanyName[.='Google']").Any()
    select contact;

否則,使用LINQ:

var query =
    from contact in doc.Elements("phoneBook").Elements("Contact")
    where contact.Elements("Company").Elements("CompanyName")
        .Any(c => (string)c == "Google")
    select contact;

暫無
暫無

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

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