简体   繁体   English

从 C# 中的 XML 文件中获取键的值

[英]Getting a value of a key from an XML file in C#

I have an XML file with the following structure:我有一个具有以下结构的 XML 文件:

<Definitions>
  <Definition Execution="Firstkey" Name="Somevalue"></Definition>
  <Definition Execution="Secondkey" Name="Someothervalue"></Definition>
</Definitions>

How can I get the values of the keys (Firstkey, Secondkey) and write them down using C# in my .NET application?如何在我的 .NET 应用程序中获取键(Firstkey、Secondkey)的值并使用 C# 将它们写下来?

Thanks.谢谢。

Using Linq to XML this is straightforward.使用 Linq 到 XML 这很简单。

To just get the keys:只需获取密钥:

var keys = doc.Descendants("Definition")
              .Select(x => x.Attribute("Execution").Value);
foreach (string key in keys)
{
    Console.WriteLine("Key = {0}", key);
}

To get all values:获取所有值:

XDocument doc = XDocument.Load("test.xml");
var definitions = doc.Descendants("Definition")
                     .Select(x => new { Execution = x.Attribute("Execution").Value,
                                        Name = x.Attribute("Name").Value });
foreach (var def in definitions)
{
    Console.WriteLine("Execution = {0}, Value = {1}", def.Execution, def.Name);
}

Edit in response to comment:编辑以回应评论:

I think what you really want is a dictionary, that maps from a key ("Execution") to a value ("Name"):认为你真正想要的是一个字典,它从一个键(“执行”)映射到一个值(“名称”):

XDocument doc = XDocument.Load("test.xml");
Dictionary<string, string> dict = doc.Descendants("Definition")
                                     .ToDictionary(x => x.Attribute("Execution").Value, 
                                                   x => x.Attribute("Name").Value);
string firstKeyValue = dict["Firstkey"]; //Somevalue

Using XMLDocumnet/XMLNode(s):使用 XMLDocumnet/XMLNode(s):

//Load the XML document into memory
XmlDocument doc = new XmlDocument();
doc.Load("myXML.xml");

//get a list of the Definition nodes in the document
XmlNodeList nodes = doc.GetElementsByTagName("Definition");

//loop through each node in the XML
foreach (XmlNode node in nodes)
{
   //access the key attribute, since it is named Execution,
   //that is what I pass as the index of the attribute to get
   string key = node.Attributes["Execution"].Value;

   //To select a single node, check if we have the right key
   if(key == "SecondKey") //then this is the second node
   {
      //do stuff with it
   }
}

basically you load the xml into a document variable, select the nodes you wish to view.基本上,您将 xml 加载到文档变量 select 您要查看的节点中。 Then iterate through them and store pertinent information.然后遍历它们并存储相关信息。

using System.Xml.Linq;

var keys = XDocument.Load("path to the XML file")
.Root
.Elements()
.Select(x => x.Attribute("Execution"));

XPath would be a great choice, I'd say. XPath将是一个不错的选择,我会说。

Below is a sample XPath expression.下面是一个示例 XPath 表达式。

//Definition[@Execution='Firstkey']/@Name

As a XPath expression is a string, you can easily replace 'Firstkey' with whatever you need.由于 XPath 表达式是一个字符串,您可以轻松地将“Firstkey”替换为您需要的任何内容。

Use this with a XmlDocument.SelectSingleNode or XmlDocument.SelectNodes method将此与XmlDocument.SelectSingleNodeXmlDocument.SelectNodes方法一起使用

Both the above mentioned methods return an XmlNode.上述两种方法都返回一个 XmlNode。 You can easily access the XmlNode.Value您可以轻松访问XmlNode.Value

Here are some XPath expressions下面是一些 XPath 表达式

Don't forget XPath Visualizer which makes working with XPath so much easier!不要忘记XPath Visualizer ,它使 XPath 的工作变得如此轻松!

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

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