如何用LINQ-to-XMLselect一个特定的节点
我可以select第一个客户节点,并使用下面的代码更改公司名称。
但是,如何selectID = 2的客户节点呢?
XDocument xmldoc = new XDocument( new XDeclaration("1.0", "utf-8", "yes"), new XComment("These are all the customers transfered from the database."), new XElement("Customers", new XElement("Customer", new XAttribute("ID", 1), new XElement("FullName", "Jim Tester"), new XElement("Title", "Developer"), new XElement("Company", "Apple Inc.") ), new XElement("Customer", new XAttribute("ID", 2), new XElement("FullName", "John Testly"), new XElement("Title", "Tester"), new XElement("Company", "Google") ) ) ); XElement elementToChange = xmldoc.Element("Customers").Element("Customer").Element("Company"); elementToChange.ReplaceWith(new XElement("Company", "new company value..."));
回答:
感谢大家,为了logging,这里是在customer-with-id-2元素中search公司元素的确切语法,然后只更改公司元素的值:
XElement elementToChange = xmldoc.Element("Customers") .Elements("Customer") .Single(x => (int)x.Attribute("ID") == 2) .Element("Company"); elementToChange.ReplaceWith( new XElement("Company", "new company value...") );
解答方法语法:
只是在方法语法中弄明白了:
XElement elementToChange = (from c in xmldoc.Element("Customers") .Elements("Customer") where (int)c.Attribute("ID") == 3 select c).Single().Element("Company");
假设ID是唯一的:
var result = xmldoc.Element("Customers") .Elements("Customer") .Single(x => (int?)x.Attribute("ID") == 2);
您也可以使用First
, FirstOrDefault
, SingleOrDefault
或Where
,而不是Single
来SingleOrDefault
不同的情况。
我会使用像这样的东西:
dim customer = (from c in xmldoc...<Customer> where c.<ID>.Value=22 select c).SingleOrDefault
编辑:
错过了C#标签,对不起……这个例子是在VB.NET中