What I have
An XML doc where the node names have a strict naming convention where each node's level is reflected in its name, as follows:
<root>
<ABC>
<ABC_1/>
<ABC_2>
<ABC_2_1>
<ABC_2_1_1/>
</ABC_2_1>
<ABC_2_2/>
<ABC_2_5/>
<ABC_2_6/>
</ABC_2>
</ABC>
<DEF>
<DEF_1/>
<DEF_2/>
<DEF_59/>
</DEF>
...
</root>
The order of siblings is always preserved (as shown), but is not always sequential, i.e. some nodes may be missing (e.g. "ABC_2_3" and "ABC_2_4" above). But whatever nodes do exist, are always inserted in ascending order.
What I'm trying to do
I have a simple XPath for one of those missing nodes, e.g. "//ABC_2_4", and I need to create/insert a new node with that name if it doesn't already exist. I don't have the parent node or any other information; I only have that XPath string, and the XML document/object.
So what I do is parse that XPath to extract the parent node name (in this example "ABC_2"), and then insert a new "ABC_2_4" node into that parent node. (Let's assume for simplicity that the parent node will always exist.)
Question
Is there any "trick" to finding the previous sibling quickly, i.e. with just one or two queries somehow, instead of enumerating backwards from the missing node name and trying to select a node at a time until the existing preceding sibling is found? If I need to insert "DEF_58" node given the example XML above (i.e. between "DEF_2" and "DEF_59"), that would be a very long/slow enumeration until I find the existing preceding sibling ("DEF_2")...
Couple of notes (in case that might help):
- This naming convention makes all nodes uniquely named (the "ABC", "DEF", etc. parent prefixes are always unique).
- The depth doesn't go past what is shown in the above sample XML, i.e. "ABC_2_1_1" is the "deepest" level possible.
Thank you!