我有一个具有以下结构的 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/