XML Select xmlNode depending on innertext

I have a 'xmlDocument'-Object, which contains this structure:

<Projects>
  <Project>
    <Name>Value1</Name>
  </Project>
  <Project>
    <Name>Value2</Name>
  </Project>
</Projects>

I need to change these values on runtime via c#. My thought was

  • create new 'xmlnode'-Object
  • Change its innertext
  • save the document

But I don't know how to select the xml-node depending on its innertext. I researched a bit, and tried that:

XmlNode nameNode = doc.SelectSingleNode("Projects\\Project\\Name[text()='" + projectName + "']");

which causes 'XPathException'.

How do you write the path on the right way?

Jon Skeet
people
quotationmark

I would suggest using LINQ to XML instead of XPath:

XDocument doc = ...; // However you load the XML
XElement element = doc.Root
                      .Elements("Project")
                      .Elements("Name")
                      .Where(x => x.Value == projectName)
                      .SingleOrDefault();
// Check whether or not element is null (if so, you haven't found it)

people

See more on this question at Stackoverflow