MKFein MKFein - 7 months ago 41 Question

Dynamic version of vb SelectSingleNode

I know that with

book = root.SelectSingleNode("descendant::bk:book[bk:author/bk:last-name='Atwood']", nsmgr);

it is possible to adress elements inside a xml file in a static manner.

Is there a way to use a similar scheme but with dynamic adressing. E.g. where'Atwood' is not a const string rather than a dynamic string.

Thanks for helping.

Btw: Example from Microsoft help site


XPath expression that SelectSingleNode() receives is just a string. You should be able to use any approach applicable for constructing string dynamically in VB i.e simple string concatenation :

lastname = "Atwood"
query = "descendant::bk:book[bk:author/bk:last-name='" & lastname & "']"
book = root.SelectSingleNode(query, nsmgr)

... String.Format() as mentioned in the comment :

lastname = "Atwood"
query = "descendant::bk:book[bk:author/bk:last-name='{0}']"
book = root.SelectSingleNode(String.Format(query, lastname), nsmgr)

... or using new feature from VB 14, the string interpolation :

lastname = "Atwood"
query = $"descendant::bk:book[bk:author/bk:last-name='{lastname}']"
book = root.SelectSingleNode(query, nsmgr)

For reference :