我可以选择第一个客户节点并使用下面的代码更改其公司名称.
但是如何选择ID = 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..."));
谢谢大家,为了记录,这里是在customer-with-id-2元素中搜索company元素的确切语法,然后只更改company元素的值:
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");
Mehrdad Afsh.. 46
假设ID是唯一的:
var result = xmldoc.Element("Customers") .Elements("Customer") .Single(x => (int?)x.Attribute("ID") == 2);
你也可以使用First
,FirstOrDefault
,SingleOrDefault
或Where
,而不是Single
针对不同情况.
假设ID是唯一的:
var result = xmldoc.Element("Customers") .Elements("Customer") .Single(x => (int?)x.Attribute("ID") == 2);
你也可以使用First
,FirstOrDefault
,SingleOrDefault
或Where
,而不是Single
针对不同情况.