c++ 读取xml文件的内容

标签 c++ xml tinyxml

我仍在学习 c++,需要一些帮助来阅读 xml 文件的内容。
这是我的 xml 文件的格式:

<Rotary>
  <UserInformation>
    <Name>myName</Name>
    <Age>myAge</Age>
  </UserInformation>
</Rotary>
我的 c++ 程序需要读取 Name 和 Age 的值,以便我可以在 SQL DB 上检查它。我真的很难使用 tinyxml。有人给了我一些代码来帮助我,但我仍然没有得到它。下面是代码:
    TiXmlHandle docHandle(&doc);

    string tinyData = "null";

    TiXmlNode* tinySet = docHandle.FirstChild("Rotary").FirstChild("UserInformation").ToNode();

    if (tinySet)
    {
        for (TiXmlNode* tinyChild = tinySet->FirstChild(); tinyChild; tinyChild = tinyChild->NextSibling())
        {
            if (tinyChild)
            {
                if (tinyChild->TINYXML_ELEMENT != tinyChild->Type())
                {
                    continue;
                }
                //TODO: Change this to reflect my xml structure. Past this point I'm not sure what I'm doing.
                tinyData = tinyChild->ToElement()->Attribute("Name");

                if (strcmp(tinyData.c_str(), "Name") == 0)
                {
                    localName = tinyChild->ToElement()->FirstChild()->Value();
                }
                else if (strcmp(tinyData.c_str(), "Age") == 0)
                {
                    localAge = tinyChild->ToElement()->FirstChild()->Value();
                }
            }
        }
    }
任何帮助将不胜感激!

最佳答案

呃。该 API 看起来非常复杂。 TinyXML 是为性能而设计的,但实际上没有别的。
所以。选择图书馆是最重要的一步:What XML parser should I use in C++?
现在,在大多数可以使用 TinyXML 的情况下,您都可以使用 PugiXML。 PugiXML 有一个更友好的界面。最重要的是,它不易出错(例如,w.r.t 资源管理)。它还支持 XPath。
这在这里很有帮助。因为,以我的拙见,一旦您发现自己在节点上循环¹,案例就会丢失。你最终会得到 christmas tree code并且很难得到正确或维护。
这是我对 PugiXML 的看法:

#include <pugixml.hpp>
#include <iostream>
using namespace pugi;

int main() {
    xml_document doc;
    doc.load_file("input.xml");
    
    auto rotary = doc.root();
    // rotary.print(std::cout); // prints the entire thing

    auto name = rotary
        .select_single_node("//UserInformation/Name/text()")
        .node();
    auto age =  rotary
        .select_single_node("//UserInformation/Age/text()")
        .node();

    std::cout << "\nName is " << name.value() << "\n";
    std::cout << "Age is " << age.text().as_double() << "\n";
}
它仍然很棘手(主要是元素文本是子 text 节点的部分,您可以使用不同的方法获得这些节点)。但至少最终结果是可以合理维护的。哦,它打印:
<Rotary>
    <UserInformation>
        <Name>myName</Name>
        <Age>42.7</Age>
    </UserInformation>
</Rotary>

Name is myName
Age is 42.7
这段代码没有泄漏。

(¹甚至没有提到 TinyXML 使用的糟糕的界面......)

关于c++ 读取xml文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62602785/

相关文章:

c++ - Visual Studio 2005 和 Tinyxml - xml 文件位置

c++ - C++ main() 的第三个环境变量参数有什么用?

c++ - 加载巨大 XML 文件时的内存管理

Android:如何通过 xml 中的操作栏从首选项子屏幕导航回来?

java - spring-security-samples-preauth-xml 示例无法运行

c++ - pugixml 与 tinyxml

c++ - 使用tinyxml创建xmlns

c++ - DirectX:2 个 Sprite 多边形之间的小失真

c++ - 十进制本身转换为十六进制

Python XML : get direct child nodes