如何在OpenCV FileStorage的XML嵌套节点中写入值?
I want to write multiple values (Value_1,…,Value_N) into nested nodes of an XML file using OpenCV::FileStorage, targeting the following XML structure:
<?xml version="1.0"?> <opencv_storage> <A> <B> <Value_1>1</Value_1> … <Value_N>N</Value_N> </B> </A> </opencv_storage>What's the correct C++ code to achieve this? Also, is the following approach feasible?
FileStorage fs(file, FileStorage::APPEND); fs << "A->B->Value_1" << 1; // ??? … fs << "A->B->Value_N" << N; // ???
First off, that A->B->Value_X syntax won't work with OpenCV's FileStorage. The API doesn't support path-style direct access to nested nodes like that — you have to explicitly open and close each nested node using curly braces { and } to define the hierarchy.
Here's the correct C++ code to generate your target XML structure:
#include <opencv2/opencv.hpp> #include <string> #include <iostream> int main() { const int N = 5; // Replace with your actual number of values const std::string file_path = "output.xml"; // Open FileStorage in WRITE mode (creates new file, overwrites if exists) // Use FileStorage::APPEND only if you need to add to a valid existing OpenCV XML cv::FileStorage fs(file_path, cv::FileStorage::WRITE); if (!fs.isOpened()) { std::cerr << "Failed to open file for writing!" << std::endl; return -1; } // Start the <A> node fs << "A" << "{"; // Start the <B> node inside <A> fs << "B" << "{"; // Write Value_1 to Value_N dynamically for (int i = 1; i <= N; ++i) { std::string value_key = "Value_" + std::to_string(i); fs << value_key << i; } // Close the <B> node fs << "}"; // Close the <A> node fs << "}"; // FileStorage auto-closes when it goes out of scope, but you can call fs.release() explicitly if needed return 0; }
Key Details:
- Node Hierarchy Control: The curly braces
{and}are how FileStorage identifies nested nodes. You open a node with"{"and must close it with"}"to maintain valid XML structure. - Mode Selection: Use
cv::FileStorage::WRITEfor creating a new file. If you need to append to an existing valid OpenCV XML, useFileStorage::APPEND— but note that appending requires you to first navigate to the existing<A><B>node (you'd need to read the existing structure first to modify it safely). - Dynamic Key Generation: The loop uses
std::to_stringto create theValue_Xkeys on the fly, which is ideal if your N value is variable.
If your goal was to append values to an already existing <A><B> node (rather than creating it from scratch), you'd need to read the entire existing file into a data structure, add the new values, then write the updated structure back — OpenCV's FileStorage doesn't support direct in-place appending to nested nodes via a path shortcut.
内容的提问来源于stack exchange,提问作者N.R.

