How can i fetch the 'Value' from the keyvalue pair using c#

孤街醉人 提交于 2019-12-02 13:35:07

You can parse parameters dictionary (that is natural way to store key-value pairs) with LINQ to XML:

var xdoc = XDocument.Load(path_to_xml);
var parameters = xdoc.Descendants("Parameter")
                     .ToDictionary(p => (string)p.Attribute("Name"),
                                   p => (string)p.Attribute("Value"));

var stage = parameters["SID_STAGE"];

Keep in mind, that you should check if parameter exists in dictionary before getting it (if it is possible that parameter can not be in your xml):

if (parameters.ContainsKey("SID_STAGE"))
    // get parameter value

Also with XPath you can make query more concrete (if it is possible that somewhere will be another Parameter elements):

var xpath = "DrWatson/Sets/Set/APIParameters/Parameter";
var parameters = xdoc.XPathSelectElements(xpath)
                     .ToDictionary(p => (string)p.Attribute("Name"),
                                   p => (string)p.Attribute("Value"));
var result = XElement.Parse(xmlString)
                     .Descendants("Parameter")
                     .First(node => (string)node.Attribute("Name") == "SID_STAGE")
                     .Attribute("Value");

Console.WriteLine(result.Value); //prints 101198

Will throw an exception of element with this attribute is absent. Consider using FirstOrDefault if you would like another behaviour.

Use a LINQ to XML query:

var xml = XDocument.Load("path...");
var foo = (from n in xml.Descendants("APIParameters")
           where n.Element("Parameter").Attribute("Name").Value == "SID_STAGE"
           select n.Element("Parameter").Attribute("Value").Value).FirstOrDefault();

Gives:

101198

using System;
using System.Xml.Linq;
using System.Web;
namespace YourProjectName
{
    public static class XmlFileRetrieve
    {
        public static string GetParameterValue(string name)
        {
            try
            {
                string path = HttpContext.Current.Server.MapPath("~/YourFolderName/YourXmlFileName.xml");
                XDocument doc = XDocument.Load(path);
                if (!(doc == null))
                {
                    var parameter = (from el in doc.Root.Elements("Parameter")
                                where (string)el.Attribute("Name") == name
                                select (string)el.Attribute("value")).Select(keyvalue => new { name = keyvalue }).Single(); ;
                    return parameter.name;
                }
                return "";
            }
            catch (Exception e)
            {string error=e.Message;return "";
            }
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!