如何在C#中从XML读取键值

Man*_*ngh 3 c# xml

我有下面的xml格式文件调用"ResourceData.xml".

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <key name="customPageTitle">
    <value>Publish Resources to Custom Page</value>
  </key>
</root>
Run Code Online (Sandbox Code Playgroud)

现在我想编写一个函数,它将键"name"作为输入并返回其值元素数据,在上面的情况下,"Publish Resources to Custom Page"如果我们传递键名"customPageTitle",它将返回,我认为将打开XML文件,然后它将读取.

请建议!!

Arr*_*abi 6

请尝试以下代码:

public string GetXMLValue(string XML, string searchTerm)
{
  XmlDocument doc = new XmlDocument();
  doc.LoadXml(XML);
  XmlNodeList nodes = doc.SelectNodes("root/key");
  foreach (XmlNode node in nodes)
  {
    XmlAttributeCollection nodeAtt = node.Attributes;
    if(nodeAtt["name"].Value.ToString() == searchTerm)
    {
      XmlDocument childNode = new XmlDocument();
      childNode.LoadXml(node.OuterXml);
      return childNode.SelectSingleNode("key/value").InnerText;
    }
    else
    {
      return "did not match any documents";
    }
  }
  return "No key value pair found";
}
Run Code Online (Sandbox Code Playgroud)