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 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使用的残酷接口...
相关文章:
- 正在将csv文件读取为双精度矢量
- 将从格式化文本文件读取的文本数据存储到链表
- C++ 读取文件读取文件不正确
- 使用对象文件读取三角形数据网格
- 如何减慢从 BVH 文件读取的 opengl 动画?
- 从文件读取,并写入函数C++中的数组
- 从对象C++中的文件读取内容时出现分段错误
- 从文件读取并通过矢量输出到控制台
- 尝试将字符串从文件读取到无符号字符向量中
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 简化文件读取的函数
- 如何将逗号分隔的文件读取为 2D int 数组?
- 在 c++ 中将数据从文件读取到队列中
- 'std::wstring_convert'尽可能多地转换(从 UTF8 文件读取块)
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 文件读取C++包括空格键
- 从文件读取时未将值推回矢量
- 从文件 C++ 读取时的无限循环
- 从同一文件读取和写入?
- 从.txt文件读取到C++中的双精度向量