TinyXML2 -在XML中间插入元素
TinyXML2 - insert element in middle of XML
我希望将带有数据的新元素添加到XML结构的中间。我如何在需要的地方添加它们?
当前代码:
XMLElement *node = doc.NewElement("timeStamp");
XMLText *text = doc.NewText("new time data");
node->LinkEndChild(text);
doc.FirstChildElement("homeML")->FirstChildElement("mobileDevice")->FirstChildElement("event")->LinkEndChild(node);
doc.SaveFile("homeML.xml");
我的XML结构的一个例子:
<mobileDevice>
<mDeviceID/>
<deviceDescription/>
<units/>
<devicePlacement/>
<quantisationResolution/>
<realTimeInformation>
<runID/>
<sampleRate/>
<startTimeStamp/>
<endTimeStamp/>
<data/>
</realTimeInformation>
<event>
<mEventID/>
<timeStamp/>
<data/>
<support/>
</event>
</mobileDevice>
我希望在mEventID
和data
之间的mobileDevice->event
下添加额外的timeStamp
标签,此时它们被附加在support
标签之后,我如何才能将它们输入正确的位置?
运行时当前位置:
<mobileDevice>
<mDeviceID/>
<deviceDescription/>
<units/>
<devicePlacement/>
<quantisationResolution/>
<realTimeInformation>
<runID/>
<sampleRate/>
<startTimeStamp/>
<endTimeStamp/>
<data/>
</realTimeInformation>
<event>
<mEventID/>
<timeStamp/>
<data/>
<support/>
<timeStamp>new time data</timeStamp>
</event>
</mobileDevice>
您希望使用InsertAfterChild()
来完成此操作。这里有一个你想要的例子(假设"mobileDevice"是你文档的根元素):
// Get the 'root' node
XMLElement * pRoot = doc.FirstChildElement("mobileDevice");
// Get the 'event' node
XMLElement * pEvent = pRoot->FirstChildElement("event");
// This is to store the element after which we will insert the new 'timeStamp'
XMLElement * pPrecedent = nullptr;
// Get the _first_ location immediately before where
// a 'timeStamp' element should be placed
XMLElement * pIter = pEvent->FirstChildElement("mEventID");
// Loop through children of 'event' & find the last 'timeStamp' element
while (pIter != nullptr)
{
// Store pIter as the best known location for the new 'timeStamp'
pPrecedent = pIter;
// Attempt to find the next 'timeStamp' element
pIter = pIter->NextSiblingElement("timeStamp");
}
if (pPrecedent != nullptr)
{
// Build your new 'timeStamp' element,
XMLElement * pNewTimeStamp = xmlDoc.NewElement("timeStamp");
pNewTimeStamp->SetText("Your data here");
// ..and insert it to the event element like this:
pEvent->InsertAfterChild(pPrecedent, pNewTimeStamp);
}
这是一个有趣且可能常见的用例。我在几个月前编写了一个TinyXML2教程,所以我将把这个添加到其中。
相关文章:
- 如何在向量数组中插入元素?
- 有没有更快的方法可以在 std::vector 中插入元素
- 映射C++按值排序和插入元素
- 如何在一对集合的向量中插入元素?vector<pair<int,set<string>>>
- 当索引位于末尾和空数组时,向数组插入元素时出现问题
- 在 QSet 中插入元素<QString>并检索 ,删除 QSet 的最后一项
- C++ 在列表末尾插入元素的列表的 STL 向量
- 插入元素后矢量容量增加
- 如何在 c++ 集中插入元素,直到按下 Enter 键
- C++向量插入元素
- 有没有办法在unordered_map的某个位置插入元素
- 重新插入元素可以"re-validate"迭代器吗?
- 内部源代码 - 在链接列表实现中插入元素上的删除会破坏整个应用程序
- 在链表中插入元素
- stl 中是否有任何数据结构可以在 O(1) 或 O(log n) 中插入元素,我可以在其上编写自己的bin_searc
- 如何在将数据结构插入元素后继续迭代数据结构
- 有没有一种方法可以在std::向量的特定位置重复插入元素
- 在向量 (C++) 中保留插入元素的地址
- 插入元素后Unordered_map变空,我做错了什么
- 循环a std :: unordered_map,序列始终是i插入元素的序列