Really hard to fit the explanation into an accurate title but I tried.
Anyhow the question is simple.
Given the following xml:
<Parent>
<Child/>
<Child/>
<Child/>
<Child/>
<!-- Trying to insert an element here -->
<OtherChild/>
<OtherChild/>
<OtherChild/>
</Parent>
And assuming the following:
- We know the schema and have access to it.
- All elements are optional according to the schema but must appear in order.
- The element we are inserting may be optional as well.
- There are no guarantees that any of the parents or other child nodes are there or how many there will be.
- The depth of nesting is not necessarily 1 it could be multiple nested elements.
My solution:
- Check to see if there are any of the child we are inserting.
- Recursive method to check for previous siblings (requires knowledge of the sibling that precede the element we are inserting) and then check the parent.
Results:
A. If an element that we are trying to insert exists we insert after.
B. If a preceding sibling exists we insert after.
C. If no preceding sibling exists but the parent does we prepend to the parent.
D. Walking up the tree from there we would keep going to the next parent or preceding sibling of the current parent until we find one that exists then insert the entire tree down to the element we are trying to insert.
I am currently doing this in C# code by first using the schema to discover the preceding siblings then iteratively trying to select one until I either find one or reach the end of the list. Then I try to discover the parent then repeat with the parent as the element to be inserted.
The Question:
Is it possible to do this in another, faster, more efficient, neater, better way?
I am just learning about XSLT and if it can be done with a transform that would be perfect (note must be XSLT 1.0).
Alternatively clever ways of minimising the work seeing as at present it will basically have to walk the entire tree until it reaches an existing node which could be a lot of work.
Note: For reference this is actually for use in InfoPath where I will be working on the main data source. In particular I am referring to repeating tables, it is possible for the user to delete all rows from the table at which point any code attempting to add rows to that table may have a very difficult time.
InfoPath itself is able to add new rows to the tables as easy as pie and if I could figure out how they manage it that would be great. In lieu of that I would be happy just to have a simple method for doing so.
I already have a solution to the problem, as I said I am just looking for some folk to bounce ideas off of and see if I can get some improvements. I appreciate any suggestions that you may have.
Thank you :)