c++ 读取 xml 文件的内容

c++ Read contents of xml file

我仍在学习 C++,需要一些帮助来阅读 xml 文件的内容。

这是我的 xml 文件的格式:

<Rotary>
  <UserInformation>
    <Name>myName</Name>
    <Age>myAge</Age>
  </UserInformation>
</Rotary>

我的 C++ 程序需要读取 Name 和 Age 的值,以便我可以在 SQL 数据库上检查它。我真的很难使用 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 使用的糟糕接口...)