开发者

How to read key value from XML in C#

开发者 https://www.devze.com 2023-03-03 04:15 出处:网络
I have got below xml format file called \"ResourceData.xml\". <?xml version=\"1.0\" encoding=\"utf-8\" ?>

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消