Reputation: 2529
I have an xml name as 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. For example: I want to get the value(C:/Temp/validate.xml) for the node that name (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());
Upvotes: 0
Views: 306
Reputation: 3451
In this case it might be easiest to use an XPath expression to find the item you are looking for. 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:
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}");
}
Upvotes: 2