简体   繁体   English

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

[英]How to read key value from XML in C#

I have got below xml format file called "ResourceData.xml" .我有下面的 xml 格式文件名为"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.现在我想写一个 function ,它将键"name"作为输入并返回其值元素数据,在上述情况下,如果我们传递键名"customPageTitle" ,它将返回"Publish Resources to Custom Page" ”,我想会打开 XML 文件,然后它将读取。

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.将文件加载到 XDocument 中。 Replace [input] with method input variable.将 [input] 替换为方法输入变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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