Locating XML node by child node value inside of it, and changing another value
c#, xml
Solution
Using XLinq, you can perform this query fairly naturally:
// Given:
// var xdoc = XDocument.Load(...);
// string applianceName = "Toaster";
// Find the appliance node who has a sub-element <Name> matching the appliance
var app = xdoc.Root
.Descendants("Appliance")
.SingleOrDefault(e => (string)e.Element("Name") == applianceName);
// If we've found one and it matches, make a change
if (app != null)
{
if (((string)app.Element("Model")).StartsWith("B8d-k30"))
{
app.Element("Model").Value = "B8d-k30 Mark II";
}
}
xdoc.Save(@"output.xml"); // save changes back to the document
Problem
Three part question. Is it possible to locate a specific XML node by a child inside of it to retrieve other children of the parent? Example: ``` <House> <Kitchen> <Appliance> <Name>Refrigerator</Name> <Brand>Maytag</Brand> <Model>F2039-39</Model> </Appliance> <Appliance> <Name>Toaster</Name> <Brand>Black and Decker</Brand> <Model>B8d-k30</Model> </Appliance> </Kitchen> </House> ``` So for this, I would like to locate the appropriate Appliance node by searching for "Refrigerator" or "Toaster", and retrieve the brand from it. The second part of this question is this: Is this a stupid way to do it? Would using an attribute in the Appliance tag make this a lot easier? If so, how would I locate it that way? As for the third part, once I locate the Appliance, how would I go about changing say, the Model, of that particular appliance?