简体   繁体   English

如何从 C# 获取 xml 标记值

[英]How to get the xml tag value from C#

I have an xml name as recipe.xml我有一个 xml 名称作为recipe.xml

<sections>
<section name="Template">
<item key="SkipTemplates" value="C:/Temp/skip.xm;" />
<item key="validateTemplate" value="C:/Temp/validate.xml" />
<item key="PassTemplate" value="C:/Temp/pass.xml" />
</section>
<section name="Version">
<item key="MenuTemplate" value="C:/TempVersion/menu.xml" />
<item key="PassTemplate" value="C:/TempVersion/pass.xml" />
<item key="SkipTemplate" value="C:/TempVersion/skip.xml" />
</section>
</sections>

I wish to used C# code to return me the value of each node.我希望使用 C# 代码来返回每个节点的值。 For example: I want to get the value(C:/Temp/validate.xml) for the node that name (validateTemplate)例如:我想获取该名称的节点的值(C:/Temp/validate.xml)(validateTemplate)

I have try below code but return me error:我尝试了下面的代码,但返回错误:

XmlDocument xml = new XmlDocument();
xml.Load("C:/Mani/recipe.xml");
XmlElement directoryElement = xml.GetElementById("validateTemplate");
string backupPath = directoryElement.GetAttribute("value");
MessageBox.Show(backupPath.ToString());

在此处输入图片说明

In this case it might be easiest to use an XPath expression to find the item you are looking for.在这种情况下,使用XPath 表达式来查找您要查找的项目可能是最简单的。 You can turn this into a function that uses the name of the section and item name as parameters.您可以将其转换为使用部分名称和项目名称作为参数的函数。

Something like this:像这样的东西:

var templatePath = xml.DocumentElement?.SelectSingleNode("/sections/section[@name='Template']/item[@key='validateTemplate']/@value")?.Value;

or play with it an select all section.items:或使用它选择所有 section.items:

foreach (XmlNode item in xml.DocumentElement.SelectNodes("/sections/section/item"))
{
    Console.WriteLine($"{item.ParentNode.Attributes["name"]?.Value}.{item.Attributes["key"]?.Value}\t{item.Attributes["value"]?.Value}");
}

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

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