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

标签 c# xml

我有一个具有以下结构的 XML 文件:

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

如何获取键值(Firstkey、Secondkey)并在我的 .NET 应用程序中使用 C# 记录它们?

谢谢。

最佳答案

使用 Linq to XML 这很简单。

获取 key :

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

获取所有值:

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

编辑以回应评论:

认为您真正想要的是一个字典,它从一个键(“执行”)映射到一个值(“名称”):

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

关于c# - 在 C# 中从 XML 文件中获取键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5873680/

相关文章:

PHP Soap 请求标签为空

c# - 比较两个字典中的键

c# - 如何使用owin和Mvc 5从httpcontext获取访问 token

java - 我想不通为什么这段代码不起作用(空指针异常)

mysql - 将数据从一个数据库迁移到另一个数据库

android - 即使是单次使用,我也应该使用 XML 资源吗?

c# - Invoke 在底层是如何工作的?线程不是只有 1 个指令指针吗?

c# - 如何使用 Web.config 转换更改 appSettings 部分中的属性值

c# - ASP 点网 : How to repeat HTML parts with minor differences on a page?

javascript - Node.js - 解析 XML 时方法返回 UNDEFINED