0

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 Answers2

0

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

Community
  • 1
  • 1
  • I tried that but strangely the if I add the node its there and delete deletes both. :-/ – Morten MacFly Jan 07 '17 at 15:33
  • Put your code in a github gist. I should be able to help you with this one. – Alicia Fernandez Jan 08 '17 at 05:08
  • I've created a minimal test case and a gist. (Never done that before so it took a while... :-). See here: https://gist.github.com/MortenMacFly/264e6ff0793584aca7953fba8b8a4f38 – Morten MacFly Jan 08 '17 at 12:32
  • ...I should add that what I'm trying to do is to realise the ability of including parts of a configuration into a master configuration. I can't use XInclude because the code must be minimal for an embedded platform. – Morten MacFly Jan 08 '17 at 12:35
  • I tried the last days but I give up. The problem with TinyXML2-Ex is that it requires C++14. For embedded systems this is unfortunately way to modern. I tried a system update, compiler update but this broke other things so I am back to native TinyXML2 (but didn't solve it yet). Thank you very much for you help anyways, its definitely appreciated. – Morten MacFly Jan 16 '17 at 11:49
  • Right, it wasn't as trivial as I originally thought. I'll try again tonight and see if I get anywhere. – Alicia Fernandez Jan 18 '17 at 03:43
0

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.

stanthomas
  • 1,141
  • 10
  • 9