Sujit
Sujit

Reputation: 143

Append element in xml file in opencv using cpp

I am trying to append a new element in my opencv xml file which already has one element as below

<?xml version="1.0"?>
<opencv_storage>
<acc type_id="opencv-ml-ann-mlp">
...
</_></weights></acc>
</opencv_storage>

I am trying to append one more element called micr as below

<?xml version="1.0"?>
<opencv_storage>
<acc type_id="opencv-ml-ann-mlp">
...
</_></weights></acc>
  <micr type_id="opencv-ml-ann-mlp">
...
</_></weights></micr>
</opencv_storage>

But what I am getting is

<?xml version="1.0"?>
<opencv_storage>
<acc type_id="opencv-ml-ann-mlp">
...
  <micr type_id="opencv-ml-ann-mlp">
...
</_></weights></micr></_></weights></acc>
</opencv_storage>

I am using cv::FileStorage from opencv.

I want to know what is wrong with ::APPEND and if there is any alternative to achieve this.

Here's the code:

cv::FileStorage f("OCR.xml", cv::FileStorage::WRITE);
...
ann.write(*f, "acc");    //In another function
...
f.release();

cv::FileStorage f("OCR.xml", cv::FileStorage::APPEND);
...
ann.write(*f, "micr");    //In another function
...
f.release();

Thanks in advance!

Upvotes: 1

Views: 1663

Answers (1)

Miki
Miki

Reputation: 41775

Please try this snippet. It seems to work as expected.

#include <opencv2/opencv.hpp>
#include <vector>
using namespace cv;

int main()
{
    Mat layers = (Mat1i(2,1) << 5, 15);
    CvANN_MLP ann(layers);

    {
        FileStorage f("OCR.xml", FileStorage::WRITE);
        ann.write(*f, "acc");
    }
    {
        FileStorage f("OCR.xml", FileStorage::APPEND);
        ann.write(*f, "micr");
    }

    FileStorage f("OCR.xml", FileStorage::READ);

    CvANN_MLP ann_acc;
    ann_acc.read(*f, cvGetFileNodeByName(*f, NULL, "acc"));

    CvANN_MLP ann_micr;
    ann_acc.read(*f, cvGetFileNodeByName(*f, NULL, "micr"));

    return 0;

    return 0;
}

See also here that you shouldn't mix save/load with write/read.

Upvotes: 1

Related Questions