TinyXML2: Replace Node function?

763 Views Asked by At

I am having a hard time using TinyXML2 (https://github.com/leethomason/tinyxml2) to write a C/C++ method that replaces a given node like:


    <doc>
      <replace>Foo</replace>
    </doc>
...with another node:

    <replacement>Bar</replacement>
...so that the outcome is:
    <doc>
      <replacement>Bar</replacement>
    </doc>
However, the node to be replaced may appear multiple times an I would like to keep the order in case I replace the second node with something else.

This should actually be straight-forward, but I am failing with endless recursions.

Is there probably an example around of how to do that? Any help would be greatly appreciated.

2

There are 2 best solutions below

6
On BEST ANSWER

Do you have sample code?

You could try calling tinyxml2::XMLNode::InsertAfterChild to insert <replacement> followed by a deletion of <replace>.

This answer also seems related: Updating Data in tiny Xml element

0
On

I'd recommend copying the source xml to a new document using the visitor pattern making substitutions as you go. Substituting in-place is very likely to lead to broken chains and the endless loops that you're experiencing.

You can find an example of using the vistor pattern to make substutions (in element attributes and text but it's the same principle) here. See xcopy function and associated code near the bottom.