简体   繁体   中英

How to read key value from XML in C#

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!!

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";
}

Load the file into an XDocument. Replace [input] with method input variable.

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

This is untested code so there might be errors in this snippet.

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();
}
return doc.Descendants("key")
           .Where(c => ((String)c.Attribute("name")).Equals(search))
           .Select(c => (String)c.Element("value"))
           .FirstOrDefault()
           .Trim();

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.

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