Extracting sub-tree XML string with TinyXml2

三世轮回 提交于 2020-01-04 21:40:56

问题


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?


回答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(">");
}


来源:https://stackoverflow.com/questions/27726049/extracting-sub-tree-xml-string-with-tinyxml2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!