Marcel
Marcel

Reputation: 927

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

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?

Upvotes: 1

Views: 2177

Answers (2)

crookie
crookie

Reputation: 260

I realise this was asked a long time ago and an alternative solution was found, but I had similar issue and I managed to solve it using xpath by use of a XmlNodeList with the following

XmlNode root = xmlDoc.DocumentElement;

XmlNodeList nodes = root.SelectNodes("//*[local-name()='Projects'//*[local-name()='Project'//*[local-name()='Name'][text()='" + projectName + "']");

You can then loop through the XmlNodeList

foreach (XmlNode xn in nodes)....

posting in case anyone else would like to use this method

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502206

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)

Upvotes: 2

Related Questions