dotnet / Open-XML-SDK

Open XML SDK by Microsoft

Home Page:https://www.nuget.org/packages/DocumentFormat.OpenXml/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Link to previous element

RFlipper opened this issue · comments

In my scenario, I am using the action InsertBeforeSelf a lot, for small documents it works OK, but for bigger the performance degrades very fast. It occurs when you have a lot of sibling elements and doing Insert before some one of them you need to do a walk from the first.
PreviousSibling()

var firstChild = parent.FirstChild;

while (firstChild is not null)
{
      var nextSibling = firstChild.NextSibling();
      if (nextSibling == this)
      {
          return firstChild;
      }

      firstChild = nextSibling;
}

return firstChild;

So my question is: Isn't possible to add the Prev property as an opposite to Next, I believe it could improve performance. The only fear is memory consumption.

Also, during research, I have found an article about C++ pugixml they are using the following structure:

struct Node {
  Node* first_child;
  Node* prev_sibling_cyclic;
  Node* next_sibling;
};

I believe the same approach could be applied here.

So the simplest solution will be to add Prev property to OpenXmlElement and rewrite methods inserting/removing elements in OpenXmlCompositeElement.

I would be happy to hear some feedback as well as the pros and cons.

I was able to implement a workaround by caching the previous element via annotations. Therefore, I will close the issue.

@RFlipper we could probably take a PR to add this API if you're willing to do so and add some tests for it