我如何使用C#获取来自键值对的“值” [英] How can i fetch the 'Value' from the keyvalue pair using c#
问题描述
我想在取下使用C#'名称'提供的各种参数值中提到的字符串。
这是我当前的XML如下:
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>
我想取'101198'
在值
为名称= SID_STAGE
。
请建议我如何执行它。
I would like to fetch the '101198'
available under 'Value'
for Name = SID_STAGE
.
Please suggest how can i perform it.
推荐答案
您可以分析参数的字典(即存储关键自然的方式 - 值对)用的LINQ to XML:
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"];
请记住,你应该检查一下参数,在字典中存在得到它(如果可能的话之前,该参数不能在你的XML):
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
同时使用XPath可以让查询更具体的(如果可能的话在某个地方会是另一个参数元素):
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"));
这篇关于我如何使用C#获取来自键值对的“值”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!