Luke4792
Luke4792

Reputation: 455

Selecting a node if the attribute is equal to a predefined string

I'm currently using a loop which gives me a variable, which then needs to be fed into an Xpath method to get me any nodes with an attribute equal to my variable. So far, I've learned that Xpath allows you to select a node from the XML document using

root.SelectNodes("Element[@Attribute='SpecificValue']")

However, I'd like to know if there's a way I can insert a predefined variable where the specific value, so I can grab a different set of nodes with each iteration of my loop.

For example something like this:

string  attribValue= "test"
root.SelectNodes("Element[@Attribute = attribValue]")

Upvotes: 0

Views: 123

Answers (2)

jdweng
jdweng

Reputation: 34433

Using XML Linq

            XDocument doc = new XDocument();
            XElement root = (XElement)doc.FirstNode;
            string  attribValue= "test";
            var results = root.Descendants("Element").Where(x => x.Attribute("Attribute").Value == attribValue).ToList();​

Upvotes: 0

alecxe
alecxe

Reputation: 474191

Use string formatting:

string attribValue = "test";
string expression = String.Format("Element[@Attribute = '{0}']", attribValue);
root.SelectNodes(expression);

Upvotes: 1

Related Questions