正在更新微小Xml元素中的数据

Updating Data in tiny Xml element

本文关键字:元素 数据 Xml 更新      更新时间:2023-10-16

我的问题是:是否可以更改xml元素中的数据?

我想做的是根据按下的按钮来更改元素中的数据。我目前正在读取和写入xml文件,但我想将其更改为,第一次写入一个新元素,然后编辑该元素,因为它目前每次只写一个新元素。

这是我当前编写新元素的代码

if (doc.LoadFile(XMLDOC) == tinyxml2::XML_SUCCESS){
    //Get Root Node
    tinyxml2::XMLElement* rootNode = doc.FirstChildElement();//Assets
    //Get Next Node
    tinyxml2::XMLElement* childNode = rootNode->FirstChildElement();//imagePaths
    //Temp Element 
    tinyxml2::XMLElement* temp = nullptr;
    tinyxml2::XMLElement* temp2 = childNode->FirstChildElement();//path
    while (temp2 != nullptr){
        temp = temp2;
        temp2 = temp2->NextSiblingElement("path");
    }
    if (temp != nullptr){
        //write the text
        tinyxml2::XMLComment* newComment = doc.NewComment("Selected Player");
        tinyxml2::XMLElement* newElement = doc.NewElement("path");
            //get text passed in 
            newElement->SetText(choice.c_str());
            newElement->SetAttribute("name", "selected_player");
            childNode->InsertAfterChild(temp, newComment);
            childNode->InsertAfterChild(newComment, newElement);
    }
    //doc.Print();
    doc.SaveFile(XMLDOC);
    }
    else{
        std::cout << "Could Not Load XML Document : %s" << XMLDOC << std::endl;
    }
}

感谢您在高级方面的帮助

我不能100%确定您想要什么样的行为。以下是基于您的问题代码示例的代码示例:

#include "tinyxml2.h"
#include <iostream>
#include <string>
#define XMLDOC "test.xml"
std::string choice = "New Text";
int main()
{
   tinyxml2::XMLDocument doc;
   if (doc.LoadFile(XMLDOC) == tinyxml2::XML_SUCCESS){
      //Get Root Node
      tinyxml2::XMLElement* rootNode = doc.FirstChildElement();//Assets
      //Get Next Node
      tinyxml2::XMLElement* childNode = rootNode->FirstChildElement();//imagePaths
      //Path Node
      tinyxml2::XMLElement* pathNode = childNode->FirstChildElement();//path
      if (pathNode == nullptr){
         //write the text
         tinyxml2::XMLComment* newComment = doc.NewComment("Selected Player");
         tinyxml2::XMLElement* newElement = doc.NewElement("path");
         newElement->SetAttribute("name", "selected_player");
         newElement->SetText(choice.c_str());
         childNode->InsertFirstChild(newComment);
         childNode->InsertAfterChild(newComment, newElement);
      }
      else{
         pathNode->SetText(choice.c_str());
      }
      doc.SaveFile(XMLDOC);
   }
   else{
      std::cout << "Could Not Load XML Document : " << XMLDOC << std::endl;
   }
}

给定一个如下所示的XML文件:

<Assets>
<ImagePaths>
</ImagePaths>
</Assets>

运行后,它看起来像这样:

<Assets>
<ImagePaths>
    <!--Selected Player-->
    <path name="selected_player">New Text</path>
</ImagePaths>
</Assets>

如果你再次运行该程序,你只会得到一个路径节点,其中包含你的选择字符串所包含的文本。

希望能有所帮助!

相关文章: