c++ - 如何使用 TinyXML2 库在 C++ 中迭代 XML 节点

标签 c++ xml dictionary vector tinyxml2

如何在 TinyXML2 中迭代节点?我尝试按照文档进行操作,但无法理解这一点。

http://www.grinninglizard.com/tinyxml2docs/index.html

我的 XML 已经加载到 std::string 中。因此,以下编译:

#include "tinyxml2.hpp"
// assume I have code here which reads my XML into std::string sXML
tinyxml2::XMLDocument doc;
doc.Parse( sXML.c_str() );

现在我如何使用 doc 迭代项目列表,以便我可以将标题和作者字段提取到 std::string 变量中?

这是我的 XML 示例:

<?xml version=“1.0” encoding=“utf-8”?>
<books>
    <item>
        <title>Letters to Gerhardt</title>
        <author>Von Strudel, Jamath</author>
    </item>
    <item>
        <title>Swiss Systemic Cleanliness Principles, The</title>
        <author>Jöhansen, Jahnnes</author>
    </item>
</books>

希望有一些简单的东西,比如 item 的 C++ vector,然后可能是一个 C++ map,我可以在其中通过 "title""author".title.author

最佳答案

// PARSE BOOKS

#pragma once
#include <string>
#include <stdio.h>
#include <vector>
#include "tinyxml2.hpp"

struct myRec {
  std::string title;
  std::string author;
};

std::vector<myRec> recs;

tinyxml2::XMLDocument doc;
doc.Parse( sXML.c_str() );
tinyxml2::XMLElement* parent = doc.FirstChildElement("books");

tinyxml2::XMLElement *row = parent->FirstChildElement();
while (row != NULL) {
  tinyxml2::XMLElement *col = row->FirstChildElement();
  myRec rec;
  while (col != NULL) {
    std::string sKey;
    std::string sVal;
    char *sTemp1 = (char *)col->Value();
    if (sTemp1 != NULL) {
      sKey = static_cast<std::string>(sTemp1);
    } else {
      sKey = "";
    }
    char *sTemp2 = (char *)col->GetText();
    if (sTemp2 != NULL) {
      sVal = static_cast<std::string>(sTemp2);
    } else {
      sVal = "";
    }
    if (sKey == "title") {
      rec.title = sVal;
    }
    if (sKey == "author") {
      rec.author = sVal;
    }
    col = col->NextSiblingElement();
  } // end while col
  recs.push_back(rec);
  row = row->NextSiblingElement();
} // end while row
signed long nLen = recs.size();
if (nLen > 0) {
  --nLen;
  nLen = (nLen < 0) ? 0 : nLen;
  for (int i = 0; i <= nLen; i++) {
    std::string sTitle = recs[i].title;
    std::string sAuthor = recs[i].author;
    std::cout << sTitle << "\n" << sAuthor << "\n";
  }
} else {
  std::cout << "Empty rowset of books.\n";
}

请注意,我是 C++ 的新手。如果您知道用更少的行优化它的方法,我会很高兴看到它。

关于c++ - 如何使用 TinyXML2 库在 C++ 中迭代 XML 节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35410935/

相关文章:

c# - 序列化/反序列化 XML 数据时,XML 元素和类属性是否具有相同的名称?

c++ - 将字符串传递给 ns3::Ipv4AddressHelper::SetBase 方法

xml - 在具有任意结尾的元素的GO xml中解析

c++ - valgrind 中的 helgrind 提示简单的互斥锁

javascript - 获取指定父级的子级属性?

python - 如何创建按值降序排列的键列表

python - 根据另外两个列和表在 Pandas 中创建列

python - 使用 'a' 方法写入 csv : headers and new values

c++ - 使用带有动态库的 Eigen 和 Visual Studio 2013 的内存对齐错误

c++ - 将 OpenCV cv::Mat 图像流式传输到网站(html5 页面)