我仍在学习 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/