簡體   English   中英

如何從 C# 獲取 xml 標記值

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

我有一個 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>

我希望使用 C# 代碼來返回每個節點的值。 例如:我想獲取該名稱的節點的值(C:/Temp/validate.xml)(validateTemplate)

我嘗試了下面的代碼,但返回錯誤:

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

在此處輸入圖片說明

在這種情況下,使用XPath 表達式來查找您要查找的項目可能是最簡單的。 您可以將其轉換為使用部分名稱和項目名稱作為參數的函數。

像這樣的東西:

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

或使用它選擇所有 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