我有一个XML文件,结构如下:
<Definitions>
<Definition Execution="Firstkey" Name="Somevalue"></Definition>
<Definition Execution="Secondkey" Name="Someothervalue"></Definition>
</Definitions>
如何在我的.NET应用程序中使用C#获取密钥的值(Firstkey,Secondkey)并将其写下来?
感谢。
答案 0 :(得分:5)
使用Linq to XML这很简单。
要获得钥匙:
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
答案 1 :(得分:1)
使用XMLDocumnet / XMLNode:
//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
}
}
基本上你将xml加载到文档变量中,选择你想要查看的节点。然后迭代它们并存储相关信息。
答案 2 :(得分:1)
using System.Xml.Linq;
var keys = XDocument.Load("path to the XML file")
.Root
.Elements()
.Select(x => x.Attribute("Execution"));
答案 3 :(得分:1)
XPath将是一个很好的选择,我会说。
以下是XPath表达式示例。
//Definition[@Execution='Firstkey']/@Name
由于XPath表达式是一个字符串,您可以轻松地将“Firstkey”替换为您需要的任何内容。
使用XmlDocument.SelectSingleNode或XmlDocument.SelectNodes方法
上述两种方法都返回一个XmlNode。您可以轻松访问XmlNode.Value
Here are some XPath expressions
不要忘记XPath Visualizer,这使得使用XPath变得更加容易!