簡體   English   中英

使用Boost.PropertyTree從XML讀取值數組

[英]Read an array of values from XML with Boost.PropertyTree

我有這個示例XML文件:

<?xml version="1.0" ?>
<Root>
  <ChildArray>
    1.0  0.0 -1.0
  </ChildArray>
</Root>

我試圖使用Boost.PropertyTree讀取它,嘗試以下方法:

#include <array>
#include <string>
#include <iostream>
#include <exception>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>

namespace pt = boost::property_tree;

struct VectorXML
{
    std::array<float, 3> _data;
    void load(const std::string &filename);
};

void VectorXML::load(const std::string &filename)
{
    // Create empty property tree object
    pt::ptree tree;

    // Parse the XML into the property tree.
    pt::read_xml(filename, tree);

    _data=
        tree.get<std::array<float, 3>>("Root.ChildArray");
}

int main()
{
    try
    {
        VectorXML v;
        v.load("data.xml");
        std::cout << "Success\n";
        std::cout
            << "X: " << v._data[0] << " "
            << "Y: " << v._data[1] << " "
            << "Z: " << v._data[2] << "\n";
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << "\n";
    }
    return 0;
}

但它沒有編譯( stream_translator.hpp中的>> overload不接受std::array s)。

我想我將不得不手動迭代數據但我無法想出從這個節點檢索數據的方法,文檔不清楚如何訪問具有多於1個值的節點中的數據...

就像是

for (size_t i = 0; i < 3; ++i)
    _data[i] = tree.get<float>("Root.ChildMatrix.???");

但它不起作用(節點有3個浮點數,並且boost無法轉換為“float”)。

好吧,這很容易,我是一個不再嘗試更多的白痴。 如果有人發布更好的答案,我不會將此標記為答案。

我已經擴展了答案以適應任何維度的矩陣(假設您將屬性Size="MN"到節點)。

回答原始問題

std::stringstream iss(
    tree.get_child("Root.ChildArray")
        .data() // string
);
float number = 0;
for (size_t i = 0; i < 3; i++)
    if (iss >> number)
        _data[i] = number;

擴展答案

在這里,我添加了一個屬性檢查來讀取尺寸(請注意,這可以改進,特別是對於更多尺寸,這個仍然使用array<float,3>而不是完全動態的容器)。

// probably can be done in a more elegant way
std::stringstream iss(
    tree.get<std::string>("Root.ChildArray.<xmlattr>.Dimensions")
);
size_t M = 0;
iss >> M;
// *********
iss.str(
    tree.get_child("Root.ChildArray")
        .data()
);
_data.resize(M);
float number = 0;
for (size_t row = 0; row < M; row++)
{
    for (size_t col = 0; col < 3; col++)
    {
        if (iss >> number)
        {
            _data[row][col] = number;
        }
    }
}

嘗試使用以下XML:

<?xml version="1.0" ?>
<Root>
  <ChildArray Dimensions="2 3">
    1.0  0.0 -1.0
    0.0  0.4  1.0
  </ChildArray>
</Root>

暫無
暫無

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

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