2014-07-18 67 views
0

我正在尋找在數據添加到我的XML結構中間的新元素。我如何在需要他們的地方追加他們?TinyXML2 - 在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> 

我期待它添加addtional timeStamp標籤mobileDevice->eventmEventIDdata之間,此刻他們被追加在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> 

回答

3

你想用InsertAfterChild()做到這一點。下面是應該做你想做的一個例子(假設「移動設備」是你的文檔的根元素):

// 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 tutorial,所以我會加入它。

+0

謝謝你的工作,我不得不改變一條線,因爲它是一個錯誤。 'pNewTimeStamp.SetText( 「在這裏你的數據」);' 改變過 'pNewTimeStamp->的setText( 「此處您的數據」);' – Colin747

+1

啊,好趕上。 :)在過去的幾個月中,我一直使用''替代C++的' - >',並且在運行時輸入上面的代碼,而沒有真正測試它。上面的代碼片段已更新。謝謝! :) – GameDev