How to get the XML path of an XmlNode?

M

Morten Wennevik

Hi Sharon,

I'm not aware of anything out of the box that will give you this
information, but you can easily create the path using XmlNode.Parent

// given an XmlNode node

string s = node.Name;
while (node.ParentNode != null && node.ParentNode.NodeType !=
XmlNodeType.Document)
{
node = node.ParentNode;
s = node.Name + "/" + s;
}
 
G

Guest

This is one of those examples where I would recommend a StringBuilder over a
string for building the path, especially if this code is going to be called
many times.

Mark.
 
M

Marc Gravell

Agreed; using .Insert() (or Push() each to a Stack<XmlNode> and Pop() it
afterwards, using .Append()).

Note, however, that this approach will not guarantee a usable path; for
instance, it doesn't distingusish between siblings, and doesn't allow for
namespaces, attribs, etc.

If you want this type of functionality, often a better approach is to have
an ID attribute or similar, so that you can uniquely reference the elements.

Marc
 
M

Morten Wennevik

I don't see how a StringBuilder would improve this functionality. Unless
the xml is incredibly deep (>100 subnodes) there really won't be much, or
any, improvement. If you call the code many times you won't benefit from
a StringBuilder if you have to create the StringBuilder object each time.
 
H

Hans Kesting

This is one of those examples where I would recommend a StringBuilder over a
string for building the path, especially if this code is going to be called
many times.

Mark.

My guess is that in this case it will take *longer* if you use a
StringBuilder, because the new value is added at the *beginning*.
I imagine that adding at the front of the string will involve shifting
the old string around, which might take more time that the simple
string concatenation of the original solution.

But of course the best way to decide would be to time the various
solutions, using reasonable test-data (as others said, the node will
probably not be too deep).


Hans Kesting
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top