使用TinyXml2提取子树XML字符串 [英] Extracting sub-tree XML string with TinyXml2
问题描述
我想做与这个问题.
我想将XML子元素(及其所有子元素)转换为XML字符串,所以如果XML结构是
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>
我想要子元素的xml,例如
I want the xml for the child element, e.g.
<child>
<value>abc</value>
</child>
我不在乎空格.问题在于另一个问题中的接受的答案似乎已过时,因为没有打印"方法用于XMLElement对象.我可以用TinyXml2做到这一点吗?
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?
推荐答案
我编写了以下对我有用的函数.请注意,它可能存在错误-我正在使用非常简单的XML文件,因此我不会假装已经测试了所有情况.
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(">");
}
这篇关于使用TinyXml2提取子树XML字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!