I can select the first customer node and change its company name with the code below.
But how do I select customer node where 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..."));
Thanks guys, for the record, here is the exact syntax to search out the company element in the customer-with-id-2 element, and then change only the value of the company element:
XElement elementToChange = xmldoc.Element("Customers") .Elements("Customer") .Single(x => (int)x.Attribute("ID") == 2) .Element("Company"); elementToChange.ReplaceWith( new XElement("Company", "new company value...") );
Just figured it out in method syntax as well:
XElement elementToChange = (from c in xmldoc.Element("Customers") .Elements("Customer") where (int)c.Attribute("ID") == 3 select c).Single().Element("Company");
Select XML Nodes by Name [C#] To find nodes in an XML file you can use XPath expressions. Method XmlNode. SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.
LINQ to XML is a LINQ-enabled, in-memory XML programming interface that enables you to work with XML from within the . NET programming languages. LINQ to XML is like the Document Object Model (DOM) in that it brings the XML document into memory.
Select is used to project individual element from List, in your case each customer from customerList . As Customer class contains property called Salary of type long, Select predicate will create new form of object which will contain only value of Salary property from Customer class.
The reason is, LINQ is used with C# or other programming languages, which requires all the variables to be declared first. From clause of LINQ query just defines the range or conditions to select records. So that's why from clause must appear before Select in LINQ.
Assuming the ID is unique:
var result = xmldoc.Element("Customers") .Elements("Customer") .Single(x => (int?)x.Attribute("ID") == 2);
You could also use First
, FirstOrDefault
, SingleOrDefault
or Where
, instead of Single
for different circumstances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With