There is no equivalent to getUniquePath() in the .NET XmlDocument object
model, but the docs on this method seem to indicate it does a very
simplistic calculation which is pretty easy to simulate as follows:
class NodeLocator {
private NodeLocator next;
private XmlNode node;
private NodeLocator(XmlNode node) {
this.node = node;
}
public static string GetUniqueLocation(XmlNode node) {
NodeLocator loc = new NodeLocator(node);
while (node.ParentNode != null ) {
node = node.ParentNode;
if (node is XmlDocument) break;
NodeLocator parentloc = new NodeLocator(node);
parentloc.next = loc;
loc = parentloc;
}
return loc.ToString();
}
public override string ToString() {
StringBuilder sb = new StringBuilder();
NodeLocator loc = this;
do {
sb.Append('/');
sb.Append(loc.node.Name);
sb.Append('[');
sb.Append(loc.IndexInParent);
sb.Append(']');
loc = loc.next;
} while (loc != null);
return sb.ToString();
}
private int IndexInParent {
get {
int indexInParent = 0;
XmlNode parent = node.ParentNode;
if (parent != null) {
foreach (XmlNode child in parent.ChildNodes) {
if (child == node) break;
if (child.Name == node.Name) {
indexInParent++;
}
}
}
return indexInParent;
}
}
}
This produces a path like "/x:foo[0]/x:item[1]". But this is a very
fragile XPath - any edits in the tree could break it since the hard coded
indexes [0] and [1] and so on, could now be wrong. A better XPath
expression would take into account the presence of unique ID's in the DOM
tree and use those as anchor points so that the resulting XPath location is
more robust in the face of subsequent DOM tree edits. So you would get
paths like: "/x:foo/x:item[@id='abc']". Now this XPath will work even if
you insert new items before this one, assuming the id's are still unique.
This could be done using the SchemaInfo provided on the XmlNodes and is left
as an exercise for the reader :-)
Chris.
"David Thielen" <th*****@nospam.nospam> wrote in message
news:B2**********************************@microsof t.com...
Hi;
I'm porting some java code over (that uses dom4j) and it includes the
ability to build up a new xpath using the getUniquePath() from another
select
as part of it. I can change the code to use the navigator objects but boy
will it be a PITA.
--
thanks - dave
"Oleg Tkachenko [MVP]" wrote:
David Thielen wrote:
> I may do a Select on a Select on a Select and have an XPathNavigator.
> But I
> want to later be able to get that same XPathNavigator by doing a single
> select on my original root XPathNavigator.
Why don't you just clone and save current XPathNavigator?
--
Oleg Tkachenko [XML MVP, MCAD]
http://www.xmllab.net
http://blog.tkachenko.com