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?
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.