WhiskerBiscuit
WhiskerBiscuit

Reputation: 5157

What is the proper way to build a paragraph with OpenXML?

I'm trying to create a docx file based upon an existing paragraph p. I'm not trying to clone the paragraph (eventually I want to modify the text before writing to newGraph)

Dim newGraph As New Paragraph
For Each r As Run In p
    newGraph.Append(r)
Next

Running the above code yields the following error:

Cannot insert the OpenXmlElement "newChild" because it is part of a tree.

What is the correct way of creating a new paragraph from an existing one (assuming I want to modify text along the way).

Upvotes: 1

Views: 219

Answers (1)

Chris
Chris

Reputation: 8647

As the error indicates, an instance of OpenXmlElement can not be added to multiple parents.

You can:

  • clone each Run, modify them and then add them to your new paragraph.

    Dim newGraph As New Paragraph
    For Each r As Run In p
       Dim newRun = r.Clone()
       ''make some changes here
       newGraph.Append(newRun)
    Next
    
  • or clone the entire paragraph and then loop into each Run if you want to modifiy them...

    Dim newGraph As Paragraph = Ctype(p.Clone, Paragraph)
    For Each r As Run In newGraph.Descendants(Of Run)()
       ''make some changes here
    
    Next
    

Best approach depends of what you want to do exactly (clone all attributes or not).

Remarks from MSDN:

Cloning an OpenXmlNode copies all attributes and their values, including those generated by the XML processor to represent defaulted attributes. This method recursively clones the node and the subtree underneath it. Clone is equivalent to calling CloneNode(true).

Hope this helps.

Upvotes: 1

Related Questions