Given a node as the starting point in the tree, apply your favorite match
function while traversing the descendants using FirstChild, NextSibling
and ParentNode a la:
void TraverseDescendants(XmlNode node) {
XmlNode stop, child, sibling, parent;
if (node.HasChildNodes) {
stop = node;
for (;;) {
if ((child = node.FirstChild) != null) {
node = child;
}
else {
for (;;) {
if ((sibling = node.NextSibling) != null) {
node = sibling;
break;
}
else {
if ((parent = node.ParentNode) != stop) {
node = parent;
}
else {
return;
}
}
}
}
}
}
}
Note that for a flat document you can significantly simplify the above
traversal. If you're planning to match names you might want to atomize
them first into the XmlDocument.NameTable so that you can take advantage
of the pointer comparison vs. string comparison.
All other approaches listed below eventually leverage FirstChild,
NextSibling and ParentNode. Do use XmlNode.SelectNodes() over
XmlDocument.GetElementsByTagName() since the laterkeeps track of
changes in the node list.
Ion
"microsoft" <bg@bg.com> wrote in message
news:OH**************@TK2MSFTNGP09.phx.gbl...
I have a very "flat" doc structure like this
<root>
<one>
<two>
<three>
...
n <=100
</root>
And i was wondering what is the fastest method for finding the Nth sub
element of root with a specific node name.
Or the quickest way to find the node whose name might be "SixtyFive"
Would it be:
For(int i =0;i< list.Count;++i) // or foreach allowing for the poss
overhead of a call to GetEnumerator
{
if(list[i].localname == thingiwant)
{
// do stuff
}
}
or
root.GetElementsByTagName // presumably uses SelectNodes?
or
root.SelectSingleNode // presumably some overhead here setting up the
"query engine". will have to use string.parse/concat to build the query
I'm about to profile some of this, but was wondering what anyone with a
bit more expereince of this stuff would think.
TIA
bg