简体   繁体   中英

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?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM