簡體   English   中英

從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文件只是一個偽樣本,什么都不是!

無論如何,我仍然無法獲得屬性“年齡”內的整數值。 如果這不起作用,那么我應該如何使用tinyxml2從xml文檔獲取整數和浮點數?

在if語句中,您應該像這樣測試失敗:

if (titleElement->QueryIntAttribute("age", &f) != TIXML_SUCCESS )

我相信,使用的正確方法是QueryIntText而不是QueryIntAttribute您正在嘗試獲取XML節點的值,而不是屬性。

有關更多詳細信息和用法,請查閱文檔: http : //www.grinninglizard.com/tinyxml2docs/classtinyxml2_1_1_x_m_l_element.html#a8b92c729346aa8ea9acd59ed3e9f2378

這是我為解決問題所做的工作:

#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文檔中獲取整數值的方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM