从xml中获取整数和浮点值

Get integers and floats from xml

本文关键字:整数 xml 获取      更新时间:2023-10-16

我使用的是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文档中获取整数值的方式。