从xml中获取整数和浮点值
Get integers and floats from xml
我使用的是tinyxml2,我知道如何获取属性字符串,但我也想获取整数、浮点和布尔值。所以,我有这个代码:
#include <iostream>
#include <fstream>
#include <tinyxml2.h>
using namespace std;
using namespace tinyxml2;
int main()
{
XMLDocument doc;
doc.LoadFile("sample.xml");
XMLElement *titleElement = doc.FirstChildElement("specimen");
int f = -1;
if (!titleElement->QueryIntAttribute("age", &f))
cerr << "Unable to get value!" << endl;
cout << f << endl;
return 0;
}
sample.xml为:
<?xml version=1.0?>
<specimen>
<animal>
Dog
</animal>
<age>
12
</age>
</specimen>
别担心,xml文件只是一个假样本,不是真的!
无论如何,我仍然无法获得属性"age"内的整数值。如果这不起作用,那么我应该如何使用tinyxml2从xml文档中获取int和float?
我相信,正确的使用方法是QueryIntText
而不是QueryIntAttribute
——您试图获得XML节点的值,而不是属性。
有关更多详细信息和用法,请参阅文档:http://www.grinninglizard.com/tinyxml2docs/classtinyxml2_1_1_x_m_l_element.html#a8b92c729346aa8ea9acd59ed3e9f2378
在if语句中,您应该测试以下故障:
if (titleElement->QueryIntAttribute("age", &f) != TIXML_SUCCESS )
这就是我解决问题的方法:
#include <iostream>
#include <fstream>
#include <tinyxml2.h>
using namespace std;
using namespace tinyxml2;
int main()
{
XMLDocument doc;
doc.LoadFile("sample.xml");
auto age = doc.FirstChildElement("specimen")
->FirstChildElement("age");
int x = 0;
age->QueryIntText(&x);
cout << x << endl;
return 0;
}
只要说我把xml术语弄错了就足够了,所以我把属性和文本混淆了。无论如何,这就是我从xml文档中获取整数值的方式。
相关文章:
- 如何反转整数参数包
- enum是C++中的宏变量还是整数变量
- 努力将整数转换为链表。不知道我在这里做错了什么
- 整数不会重复超过随机数
- 在C++中手动调整数组大小
- 检查输入是否不是整数或数字
- C++使用整数的压缩数组初始化对象
- Cppcheck生成xml转储文件
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 将"打开的CV图像"中的"颜色"转换为整数格式
- 通过套接字[TCP]传输数据 如何在C / C ++中打包多个整数并使用send() recv()传输数据
- 如何只允许用户输入正整数
- 如何在c++中从文本文件中逐行读取整数
- C++:如何循环通过向量中的整数元素
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 序列化,没有库的整数,得到奇怪的结果
- 在一定长度后从数组中打印时缺少整数
- std::当在256字节边界上写入整数时,流的奇怪行为
- 内联程序集printf将整数解释为地址
- 从xml中获取整数和浮点值