c++ 读取 xml 文件的内容

c++ Read contents of xml file

本文关键字:文件 读取 xml c++      更新时间:2023-10-16

我仍在学习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是为性能而设计的,但实际上没有别的。

选择库是最重要的一步:我应该在C++中使用什么XML解析器?

现在,在大多数可以使用TinyXML的情况下,您可以使用PugiXML。PugiXML有一个更友好的界面。最重要的是,它不太容易出错(例如,w.r.t 资源管理(。它还支持 XPath。

这在这里有很大帮助。因为,以我的拙见,一旦您发现自己在节点上循环¹,这种情况就会丢失。你最终会得到圣诞树代码,很难得到正确或维护。

以下是我使用 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使用的残酷接口...