TinyXML2 -在XML中间插入元素

TinyXML2 - insert element in middle of XML

本文关键字:插入 元素 中间 XML TinyXML2      更新时间:2023-10-16

我希望将带有数据的新元素添加到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>

我希望在mEventIDdata之间的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教程,所以我将把这个添加到其中。