how can i use a variable in this SelectSingleNode statement
oldCd = root.SelectSingleNode("/students/student[id={0}]",id);
how can i use a variable in this SelectSingleNode statement
oldCd = root.SelectSingleNode("/students/student[id={0}]",id);
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))
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.