2

I want to do the exact same thing as the guy in this question.

I want to convert an XML child element (and all of its children) to an XML string, so if the XML structure were

<parent>
    <child>
        <value>abc</value>
    </child>
<parent>

I want the xml for the child element, e.g.

<child>
    <value>abc</value>
</child>

I don't care about whitespace. The problem is that the accepted answer from the other question appears to be out of date, because there is no "Print" method for XMLElement objects. Can I do this with TinyXml2?

Community
  • 1
  • 1
Jim Clay
  • 963
  • 9
  • 24

1 Answers1

1

I coded up the following function that does the trick for me. Please note that it may have bugs- I am working with very simple XML files, so I won't pretend that I have tested all cases.

void GenXmlString(tinyxml2::XMLElement *element, std::string &str)
{
    if (element == NULL) {
        return;
    }

    str.append("<");
    str.append(element->Value());
    str.append(">");

    if (element->GetText() != NULL) {
        str.append(element->GetText());
    }

    tinyxml2::XMLElement *childElement = element->FirstChildElement();
    while (childElement != NULL) {
        GenXmlString(childElement, str);
        childElement = childElement->NextSiblingElement();
    }

    str.append("</");
    str.append(element->Value());
    str.append(">");
}
Jim Clay
  • 963
  • 9
  • 24
  • You should now use the Accept method instead of Print (see http://stackoverflow.com/a/29175999/217893). Please don't reinvent the wheel as above! – Alastair Maw Jan 15 '16 at 17:45