John Bustos John Bustos - 1 year ago 54
C# Question

C# Evaluate multiple Xpaths against an XmlDocument

I am writing a C# program where I would like to store a series of XPath statements as strings and evaluate them against an XMLDocument (or some other C# XML structure if there's a better one for this purpose) and store the resulting values in a dictionary / object.

My challenge is that my XPaths are not being able to be evaluated.

As a very simplified example, suppose this is my XML:

<child1 Id="Id1" Name="Name1" />
<child2 Id="Id2" Name="Name2" />

and, for example, one of my XPaths is:


(Get the name of
's child element with the
attribute = "Id1")

The simplified version of the code I'm trying to write to do this would be:

var xpath = @"//a/*[@Id='Id1']/name()";
var xml = @"<root><a><child1 Id='Id1' Name='Name1' /><child2 Id='Id2' Name='Name2' /></a></root>";

var doc = new XmlDocument();
var navigator = doc.CreateNavigator();

string ChildName = (string)navigator.Evaluate(xpath);

but I am getting the error that my XPath has an invalid token - Which I'm assuming the be the

Is there any way to accomplish this using direct XPath statements rather than traversing the tree?


Answer Source

Pretty sure you just need to rearrange your XPath if I'm understanding you correctly. Try this:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download