-2

how can i use a variable in this SelectSingleNode statement

   oldCd = root.SelectSingleNode("/students/student[id={0}]",id);
Hammam Muhareb
  • 355
  • 1
  • 4
  • 11

2 Answers2

3

if id is an attribute of student element

root.SelectSingleNode(String.Format("//students/student[@id='{0}']",id))

if it is sub element

root.SelectSingleNode(String.Format("//students/student[id[text()='{0}']]",id))
L.B
  • 114,136
  • 19
  • 178
  • 224
  • knowing that "id" is a string converted to an int32 should that be a problem, i used your second line of code since its a sub child but i keep getting an error from this exact line that says "Object reference not set to an instance of an object. " do you know what this means?? – Hammam Muhareb Dec 01 '12 at 00:28
  • @HammamMuhareb: Are you sure that `root` isn't `null`? Post a short but complete program demonstrating the problem if you're still having issues. – Jon Skeet Dec 01 '12 at 08:02
  • @HammamMuhareb XML is case sensitive. Is it possible that your xml contains `Students` not `students`? – L.B Dec 01 '12 at 09:12
2

Well, you could use string.Format to create the XPath expression, as shown in L.B's answer.

Personally I wouldn't though - I'd use LINQ to XML, which doesn't mix code and data as much as using XPath. It smacks of the same problem as the normal source of SQL injection attacks.

The LINQ to XML query would be like this:

var node = doc.Root.Elements("Students")
                   .Elements("Student")
                   .Where(x => (string) x.Element("id") == id)
                   .SingleOrDefault();

(If id is an int, you could cast the XElement to int instead of string.)

I generally prefer querying with LINQ to XML over using XPath; others have different preferences, of course.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Is there an advantage to casting the XElement (assuming that x is an XElement) to a string rather than accessing it's .Value property? – Chris Dunaway Nov 29 '12 at 16:33
  • 1
    @ChrisDunaway: It means that if the element doesn't exist, you end up with `null` instead of an exception; in other words, this query will just skip `Student` elements without a nested `id` element. Whether that's desirable or not depends on the context. – Jon Skeet Nov 29 '12 at 16:40