Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read key value from XML in C#

Tags:

c#

xml

I have got below xml format file called "ResourceData.xml".

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <key name="customPageTitle">
    <value>Publish Resources to Custom Page</value>
  </key>
</root>

Now I want to write a function which take the key "name" as input and will return its value element data, in above case it will return "Publish Resources to Custom Page" if we pass the key name "customPageTitle", I think will open the XML file and then it will read.

Please suggest!!

like image 473
Manoj Singh Avatar asked Jan 19 '23 20:01

Manoj Singh


1 Answers

Please try the following code:

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";
}
like image 129
Arrabi Avatar answered Jan 27 '23 21:01

Arrabi