Reputation: 305
I have an XML document (without attributes) that is setup like this:
<variables>
<variable>
<name>Name_Value</name>
<value>Value of Entry</value>
</variable>
<variable>
<name>Name_Value2</name>
<value>Value of Entry2</value>
</variable>
</variables>
I have used LINQ to XML to get a list of all the <name>
values in the document. These name values are displayed in a listbox control in alphabetical order (which is not the order of the names in the XML document).
When an item is selected in the listbox, I want to pass the name of the item to a method that will search the XML document for that value within the <name>
node. Once found, I want to find the next node (i.e., the <value>
node) and return it's value as a string.
I've tried all sorts of things to get this information, but apparently I don't know enough about LINQ to XML to get this work. Can only provide a solution for this?
Upvotes: 2
Views: 1646
Reputation: 37660
I think an approache that uses XPath is easier to read :
using System;
using System.Linq;
using System.Xml.Linq;
using System.Xml;
using System.Xml.XPath;
public class Test
{
public static void Main()
{
var xml = XElement.Parse(@"<variables>
<variable>
<name>Name_Value</name>
<value>Value of Entry</value>
</variable>
<variable>
<name>Name_Value2</name>
<value>Value of Entry2</value>
</variable>
</variables>");
Console.WriteLine(
GetVariableValue(xml, "Name_Value")
);
Console.WriteLine(
GetVariableValue(xml, "Name_Value2")
);
}
public static string GetVariableValue(XElement xml, string variableName)
{
return xml.XPathSelectElement("variables/variable[name='" + variableName + "']/value").Value;
}
}
Upvotes: 0
Reputation: 236218
XDocument xdoc = XDocument.Load(path_to_xml);
var query = from v in xdoc.Descendants("variable")
where (string)v.Element("name") == name
select (string)v.Element("value");
This Linq query will return IEnumerbale<string>
of value elements, which matched your name. If you sure there should be no more than one variable with specified name
string value = query.SingleOrDefault();
Or in single query:
string value = xdoc.Descendants("variable")
.Where(v => (string)v.Element("name") == name)
.Select(v => (string)v.Element("value"))
.SingleOrDefault();
Upvotes: 3