How can i fetch the 'Value' from the keyva

2019-03-07 06:41发布

问题:

I would like to fetch the string mentioned in 'Value' for various parameter available under 'Name' using c#. Here is my current xml as follows:

<DrWatson>
  <Sets>
    <Set>
      <APIParameters>
        <Parameter Name="SID_STAGE" Value="101198" Required="true" />
        <Parameter Name="SID_QE" Value="Test 91817" Required="true" />
      </APIParameters>
    </Set>
  </Sets>
</DrWatson>

I would like to fetch the '101198' available under 'Value' for Name = SID_STAGE. Please suggest how can i perform it.

回答1:

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


回答2:

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.



回答3:

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



回答4:

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


标签: c# xml key-value