How to read key value from XML in C #

I have an xml 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 that takes the key "name"as input and returns the data of the value element, in the above case it will return "Publish Resources to Custom Page", if we pass the key name "customPageTitle", I think the XML file will open, and then it will read.

Please suggest !!

+3
source share
4 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";
}
+5
source

Upload the file to XDocument. Replace [input] with the input variable of the method.

var value = doc.Descendants("key")
                 .Where(k => k.Attribute("name").Value.Equals([input]))
                 .Select(e => e.Elements("value").Value)
                 .FirstOrDefault();

This is unverified code, so there may be errors in this fragment.

0
source
public static String GetViaName(String search, String xml)
{
  var doc = XDocument.Parse(xml);

  return (from c in doc.Descendants("key")
    where ((String)c.Attribute("name")).Equals(search)
    select (String)c.Element("value")).FirstOrDefault();
}
0
source
return doc.Descendants("key")
           .Where(c => ((String)c.Attribute("name")).Equals(search))
           .Select(c => (String)c.Element("value"))
           .FirstOrDefault()
           .Trim();
0
source

All Articles