【问题标题】:Changing the contents of a tag using TinyXML2 C++使用 TinyXML2 C++ 更改标签的内容
【发布时间】:2018-04-06 17:41:52
【问题描述】:

我想这样做:

  1. 加载文件。
  2. 在其中查找具有属性值的元素,就像我想查找颜色为棕色的狗标签一样。 &ltdog colour="brown"&gt
  3. 然后我想更改标签的内容。例如:从&ltdog colour="brown"&gtBaow!&lt/dog&gt&ltdog colour="brown"&gtWaow!&lt/dog&gt

所有这些都必须使用 TinyXML2 来完成。到目前为止,我只能打开文件:

XMLDocument file; file.LoadFile("file.xml");

如果你能帮助我,那就太好了。

【问题讨论】:

  • 你想通过选择一个元素和迭代子元素等来遍历 XML 文件。我们不知道你的 XML 文件的组成来给出具体的建议。
  • @Galik 您提供的链接适用于 TinyXML 1 而不是 2。

标签: c++ tinyxml2


【解决方案1】:

好的,所以你知道如何加载文件了:

XMLDocument file;
file.LoadFile("file.xml");

我们不知道您的 XML 文件的语法。但是你必须走下来扔元素。

XMLElement *pDog = file.FirstChildElement("dog");
if(pDog != null)
{
    if(pDog->Attribute("colour") == "brown)
    {
        pDog->SetText("Waow!");
    }
}

file.SaveFile("...");

正如我所提到的,您必须解析元素才能到达正确的节点。


网上readme file也表示:

查找信息。

/* ------ Example 2: Lookup information. ---- */
{
  XMLDocument doc;
  doc.LoadFile( "dream.xml" );

  // Structure of the XML file:
  // - Element "PLAY"      the root Element, which is the
  //                       FirstChildElement of the Document
  // - - Element "TITLE"   child of the root PLAY Element
  // - - - Text            child of the TITLE Element

  // Navigate to the title, using the convenience function,
  // with a dangerous lack of error checking.
  const char* title = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->GetText();
  printf( "Name of play (1): %s\n", title );

  // Text is just another Node to TinyXML-2. The more
  // general way to get to the XMLText:
  XMLText* textNode = doc.FirstChildElement( "PLAY" )->FirstChildElement( "TITLE" )->FirstChild()->ToText();
  title = textNode->Value();
  printf( "Name of play (2): %s\n", title );
}

【讨论】:

    猜你喜欢
    • 2018-06-14
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2020-03-20
    • 2017-07-10
    相关资源
    最近更新 更多