简体   繁体   English

XML - 根据内部文本选择 xmlNode

[英]XML - Select xmlNode depending on innertext

I have a 'xmlDocument'-Object, which contains this structure:我有一个 'xmlDocument'-Object,它包含以下结构:

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

I need to change these values on runtime via c#.我需要通过 c# 在运行时更改这些值。 My thought was我的想法是

  • create new 'xmlnode'-Object创建新的“xmlnode”对象
  • Change its innertext改变它的内文
  • save the document保存文档

But I don't know how to select the xml-node depending on its innertext.但我不知道如何根据其内部文本选择 xml 节点。 I researched a bit, and tried that:我研究了一下,并尝试过:

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

which causes 'XPathException'.这会导致“XPathException”。

How do you write the path on the right way?你如何以正确的方式写出路径?

I would suggest using LINQ to XML instead of XPath:我建议使用 LINQ to XML 而不是 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我意识到很久以前就有人问过这个问题,并且找到了一个替代解决方案,但是我遇到了类似的问题,我设法通过使用 XmlNodeList 使用 xpath 解决了它,如下所示

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然后您可以遍历 XmlNodeList

foreach (XmlNode xn in nodes)....

posting in case anyone else would like to use this method发布以防其他人想使用此方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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