John Bustos John Bustos - 1 year ago 48
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:

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


and, for example, one of my XPaths is:

//a/*[@Id='Id1']/name()


(Get the name of
a
's child element with the
Id
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();
doc.LoadXml(xml);
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
name()
portion.

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

Thanks!!

Answer Source

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

name(//a/*[@Id='Id1'])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download