[英]LINQ-To-XML Query on Mulitple Identical Elements
I am fairly new to LINQ and XML and am trying to work with an existing large 500k line XML file which has the same structure as the XML below. 我对LINQ和XML相当陌生,正在尝试使用现有的500k行XML文件,该文件的结构与下面的XML相同。 I have figured out how to test for multiple null XElements but am totally stuck on how to search for multiple Identical XElements.
我已经找到了如何测试多个空XElement的方法,但完全陷入了如何搜索多个相同XElement的问题。
How do I get LINQ to return just contacts that work for google? 我如何让LINQ只返回适用于Google的联系人?
Thank you all in advanced. 谢谢大家。
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;
I generally prefer to mix in a bit of XPath to write these queries, it's far more compact than the LINQ equivalent. 我通常更喜欢混用XPath来编写这些查询,它比LINQ等效文件紧凑得多。
var query =
from contact in doc.XPathSelectElements("/phoneBook/Contact")
where contact.XPathSelectElements("Company/CompanyName[.='Google']").Any()
select contact;
Otherwise, using LINQ: 否则,使用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.