From 4dad5eeb6dd03bd82e4672179983040141fbb5b7 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 08:39:19 +0100 Subject: [PATCH 1/2] Expose pugi::xml_node interop and custom node constructor in rfl::xml --- include/rfl/xml/Reader.hpp | 32 ++- include/rfl/xml/read.hpp | 41 +++- include/rfl/xml/write.hpp | 74 +++++-- tests/xml/test_pugixml_interop.cpp | 322 +++++++++++++++++++++++++++++ 4 files changed, 438 insertions(+), 31 deletions(-) create mode 100644 tests/xml/test_pugixml_interop.cpp diff --git a/include/rfl/xml/Reader.hpp b/include/rfl/xml/Reader.hpp index 6ef06975b..1d85e5b9d 100644 --- a/include/rfl/xml/Reader.hpp +++ b/include/rfl/xml/Reader.hpp @@ -2,6 +2,7 @@ #define RFL_XML_READER_HPP_ #include +#include #include #include #include @@ -51,9 +52,13 @@ struct Reader { using InputVarType = XMLInputVar; /// Compile-time flag indicating whether type T has a custom constructor from XML. - /// Currently not implemented for XML format (always false). + /// If true, the type provides a static from_xml_node(const pugi::xml_node&) + /// method returning T or rfl::Result for custom deserialization. template - static constexpr bool has_custom_constructor = false; + static constexpr bool has_custom_constructor = + (requires(const pugi::xml_node& node) { + { T::from_xml_node(node) } -> std::convertible_to>; + }); /// Retrieves an element from an XML array by index. /// In XML, arrays are represented as sibling elements with the same name. @@ -64,12 +69,12 @@ struct Reader { const size_t _idx, const InputArrayType& _arr) const noexcept { const auto name = _arr.node_.name(); size_t i = 0; - for (auto node = _arr.node_; node; node = node.next_sibling(name)) { + for (auto node = _arr.node_; node; node = node.next_sibling(name), ++i) { if (i == _idx) { return InputVarType(node); } } - return error("Index " + std::to_string(_idx) + " of of bounds."); + return error("Index " + std::to_string(_idx) + " out of bounds."); } /// Retrieves a field from an XML object by name. @@ -218,15 +223,22 @@ struct Reader { return std::visit(cast_as_node, _var.node_or_attribute_).transform(wrap); } - /// Uses a type's custom constructor to deserialize from XML. - /// Currently not implemented for XML format. - /// @tparam T The type to construct - /// @param _var The XML value to deserialize from - /// @return Error indicating this feature is not yet implemented + /// Uses a type's custom constructor to deserialize from an XML node. + /// Calls the type's static from_xml_node(const pugi::xml_node&) method. + /// @tparam T The type to construct, must have a from_xml_node() static method + /// @param _var The XML value to deserialize from (must be a node, not an attribute) + /// @return Result containing the constructed object, or an error if construction fails template rfl::Result use_custom_constructor( const InputVarType _var) const noexcept { - return error("TODO"); + const auto call_ctor = [](const pugi::xml_node& _node) -> rfl::Result { + try { + return T::from_xml_node(_node); + } catch (const std::exception& e) { + return error(e.what()); + } + }; + return cast_as_node(_var.node_or_attribute_).and_then(call_ctor); } private: diff --git a/include/rfl/xml/read.hpp b/include/rfl/xml/read.hpp index 499d18eaf..247355b10 100644 --- a/include/rfl/xml/read.hpp +++ b/include/rfl/xml/read.hpp @@ -33,6 +33,44 @@ auto read(const InputVarType& _var) { return Parser::read(r, _var); } +/// Parses an object from a pugixml node (subtree). +/// If the node is a document node, its root element is parsed. +/// @tparam T The type to parse into +/// @tparam Ps Processors to apply during parsing (transforms the data) +/// @param _node The pugixml node to parse from +/// @return Result containing either the parsed object of type T or an error message +template +Result read(const pugi::xml_node& _node) { + if (!_node) { + return error("XML node is empty."); + } + if (_node.type() == pugi::node_document) { + for (auto child = _node.first_child(); child; + child = child.next_sibling()) { + if (child.type() == pugi::node_element) { + return read(InputVarType(child)); + } + } + return error("XML document has no root element."); + } + return read(InputVarType(_node)); +} + +/// Parses an object from a pugixml document. +/// Parses the document's root element (skipping declarations, comments, etc.). +/// @tparam T The type to parse into +/// @tparam Ps Processors to apply during parsing (transforms the data) +/// @param _doc The pugixml document to parse from +/// @return Result containing either the parsed object of type T or an error message +template +Result read(const pugi::xml_document& _doc) { + const auto root = _doc.document_element(); + if (!root) { + return error("XML document has no root element."); + } + return read(InputVarType(root)); +} + /// Parses an object from XML using reflection. /// This function reads an XML string and constructs a C++ object using compile-time reflection. /// @tparam T The type to parse into @@ -47,8 +85,7 @@ Result read(const std::string_view _xml_str) { return error("XML string could not be parsed: " + std::string(result.description())); } - const auto var = InputVarType(doc.first_child()); - return read(var); + return read(doc); } /// Parses an object from a stringstream containing XML. diff --git a/include/rfl/xml/write.hpp b/include/rfl/xml/write.hpp index c71d937a6..34d42cc3f 100644 --- a/include/rfl/xml/write.hpp +++ b/include/rfl/xml/write.hpp @@ -33,20 +33,47 @@ consteval auto get_root_name() { } } -/// Writes an XML representation into an ostream. -/// Uses compile-time reflection to serialize a C++ object to XML and write to a stream. +/// Writes an object as a child XML element under an existing pugixml node +/// using a runtime root element name. +/// Existing siblings, comments, and declarations in `_parent` are preserved. +/// @tparam Ps Processors to apply during serialization (transforms the data) +/// @param _obj The object to serialize to XML +/// @param _parent The parent pugixml node (or document) to append under +/// @param _root_name The name of the appended child element +/// @return The newly appended pugixml node (or an empty node if `_parent` is empty) +template +pugi::xml_node write(const auto& _obj, pugi::xml_node _parent, + const std::string& _root_name) { + if (!_parent) { + return pugi::xml_node(); + } + using T = std::remove_cvref_t; + using ParentType = parsing::Parent; + + const auto prev_last = _parent.last_child(); + const auto parent_ref = Ref::make(_parent); + auto w = Writer(parent_ref, _root_name); + + using ProcessorsType = Processors; + static_assert(!internal::no_field_names_v, + "The NoFieldNames processor is not supported for BSON, XML, " + "TOML, or YAML."); + Parser::write(w, _obj, typename ParentType::Root{}); + + return prev_last ? prev_last.next_sibling() : _parent.first_child(); +} + +/// Writes an object as a child XML element under an existing pugixml node. +/// Existing siblings, comments, and declarations in `_parent` are preserved. /// @tparam _root The name of the XML root element (defaults to type name if empty) /// @tparam Ps Processors to apply during serialization (transforms the data) /// @param _obj The object to serialize to XML -/// @param _stream The output stream to write XML to -/// @param _indent The indentation string for formatting (default: 4 spaces) -/// @return The output stream (for chaining) +/// @param _parent The parent pugixml node (or document) to append under +/// @return The newly appended pugixml node (or an empty node if `_parent` is empty) template -std::ostream& write(const auto& _obj, std::ostream& _stream, - const std::string& _indent = " ") { +pugi::xml_node write(const auto& _obj, pugi::xml_node _parent) { using T = std::remove_cvref_t; - using ParentType = parsing::Parent; constexpr auto root_name = get_root_name<_root, T>(); @@ -57,21 +84,30 @@ std::ostream& write(const auto& _obj, std::ostream& _stream, "explicit root name to rfl::xml::write(...) like this: " "rfl::xml::write<\"root_name\">(...)."); - const auto doc = rfl::Ref::make(); + return write(_obj, _parent, root_name.str()); +} - auto declaration_node = doc->append_child(pugi::node_declaration); +/// Writes an XML representation into an ostream. +/// Uses compile-time reflection to serialize a C++ object to XML and write to a stream. +/// @tparam _root The name of the XML root element (defaults to type name if empty) +/// @tparam Ps Processors to apply during serialization (transforms the data) +/// @param _obj The object to serialize to XML +/// @param _stream The output stream to write XML to +/// @param _indent The indentation string for formatting (default: 4 spaces) +/// @return The output stream (for chaining) +template +std::ostream& write(const auto& _obj, std::ostream& _stream, + const std::string& _indent = " ") { + pugi::xml_document doc; + + auto declaration_node = doc.append_child(pugi::node_declaration); declaration_node.append_attribute("version") = "1.0"; declaration_node.append_attribute("encoding") = "UTF-8"; - auto w = Writer(doc, root_name.str()); - - using ProcessorsType = Processors; - static_assert(!internal::no_field_names_v, - "The NoFieldNames processor is not supported for BSON, XML, " - "TOML, or YAML."); - Parser::write(w, _obj, typename ParentType::Root{}); + write<_root, Ps...>(_obj, doc); - doc->save(_stream, _indent.c_str()); + doc.save(_stream, _indent.c_str()); return _stream; } @@ -87,7 +123,7 @@ template std::string write(const auto& _obj, const std::string& _indent = " ") { std::stringstream stream; - write<_root, Ps...>(_obj, stream); + write<_root, Ps...>(_obj, stream, _indent); return stream.str(); } diff --git a/tests/xml/test_pugixml_interop.cpp b/tests/xml/test_pugixml_interop.cpp new file mode 100644 index 000000000..fd66af8e7 --- /dev/null +++ b/tests/xml/test_pugixml_interop.cpp @@ -0,0 +1,322 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_pugixml_interop { + +struct Item { + rfl::Attribute id; + std::string item_name; + int quantity; +}; + +TEST(xml_pugixml_interop, read_subtree_via_xpath) { + const char* xml = R"( + + + ignore me +
+ Wrong0 +
+
+ + + Widget + 7 + + untouched +
+
+)"; + + pugi::xml_document doc; + ASSERT_TRUE(doc.load_string(xml, pugi::parse_full)); + + const auto node = doc.select_node("//section[@id='main']/item").node(); + ASSERT_TRUE(node); + + const auto res = rfl::xml::read(node); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res.value().id(), "sku-42"); + EXPECT_EQ(res.value().item_name, "Widget"); + EXPECT_EQ(res.value().quantity, 7); +} + +TEST(xml_pugixml_interop, read_document_with_declaration_and_comments) { + const char* xml = R"( + + + Gadget + 3 + +)"; + + pugi::xml_document doc; + ASSERT_TRUE(doc.load_string(xml, pugi::parse_full)); + + const auto from_doc = rfl::xml::read(doc); + ASSERT_TRUE(from_doc) << from_doc.error().what(); + EXPECT_EQ(from_doc.value().id(), "doc-1"); + EXPECT_EQ(from_doc.value().item_name, "Gadget"); + EXPECT_EQ(from_doc.value().quantity, 3); + + const pugi::xml_node doc_as_node = doc; + const auto from_doc_node = rfl::xml::read(doc_as_node); + ASSERT_TRUE(from_doc_node) << from_doc_node.error().what(); + EXPECT_EQ(from_doc_node.value().id(), "doc-1"); + EXPECT_EQ(from_doc_node.value().item_name, "Gadget"); + EXPECT_EQ(from_doc_node.value().quantity, 3); +} + +TEST(xml_pugixml_interop, read_empty_node_returns_error) { + const auto res_null = rfl::xml::read(pugi::xml_node{}); + EXPECT_FALSE(res_null); + + pugi::xml_document doc; + ASSERT_TRUE(doc.load_string("")); + const auto res_missing = rfl::xml::read(doc.child("missing")); + EXPECT_FALSE(res_missing); + + pugi::xml_document empty_doc; + const auto res_empty_doc = rfl::xml::read(empty_doc); + EXPECT_FALSE(res_empty_doc); + + const pugi::xml_node empty_doc_node = empty_doc; + const auto res_empty_doc_node = rfl::xml::read(empty_doc_node); + EXPECT_FALSE(res_empty_doc_node); +} + +TEST(xml_pugixml_interop, write_splice_into_existing_node) { + pugi::xml_document doc; + ASSERT_TRUE(doc.load_string( + "" + "42", + pugi::parse_full)); + + const auto item = + Item{.id = "sku-9", .item_name = "Sprocket", .quantity = 12}; + + // Supports rvalue pugi::xml_node (e.g. doc.child("config")), compile-time + // and runtime root names, and processors. + const auto n_default = rfl::xml::write(item, doc.child("config")); + ASSERT_TRUE(n_default); + EXPECT_STREQ(n_default.name(), "Item"); + + const auto config = doc.child("config"); + const auto n_compile_time = rfl::xml::write<"custom_item">(item, config); + ASSERT_TRUE(n_compile_time); + EXPECT_STREQ(n_compile_time.name(), "custom_item"); + + const std::string runtime_tag = "runtime_item"; + const auto n_runtime = rfl::xml::write(item, config, runtime_tag); + ASSERT_TRUE(n_runtime); + EXPECT_STREQ(n_runtime.name(), "runtime_item"); + + const auto n_camel = + rfl::xml::write<"camel_item", rfl::SnakeCaseToCamelCase>(item, config); + ASSERT_TRUE(n_camel); + EXPECT_STREQ(n_camel.name(), "camel_item"); + EXPECT_STREQ(n_camel.child_value("itemName"), "Sprocket"); + const auto parsed_camel = + rfl::xml::read(n_camel); + ASSERT_TRUE(parsed_camel) << parsed_camel.error().what(); + EXPECT_EQ(parsed_camel.value().item_name, "Sprocket"); + + // Existing comment and sibling must remain intact and first. + const auto first = config.first_child(); + ASSERT_EQ(first.type(), pugi::node_comment); + EXPECT_STREQ(first.value(), " keep me "); + EXPECT_STREQ(first.next_sibling().name(), "existing"); + EXPECT_STREQ(first.next_sibling().child_value(), "42"); + + // Round-trip directly from the returned pugixml handles. + for (const auto& node : {n_default, n_compile_time, n_runtime}) { + const auto parsed = rfl::xml::read(node); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().id(), "sku-9"); + EXPECT_EQ(parsed.value().item_name, "Sprocket"); + EXPECT_EQ(parsed.value().quantity, 12); + } + + // Writing directly into a stack-allocated pugi::xml_document does not take + // ownership of the document. + pugi::xml_document standalone; + const auto root = rfl::xml::write(item, standalone); + ASSERT_TRUE(root); + EXPECT_EQ(root, standalone.document_element()); + EXPECT_EQ(rfl::xml::read(standalone).value().item_name, "Sprocket"); + + // Writing into an empty handle fails safely by returning an empty node. + EXPECT_FALSE(rfl::xml::write(item, pugi::xml_node{})); +} + +struct RichText { + std::string lang; + std::string plain; + std::vector bold_spans; + + static rfl::Result from_xml_node(const pugi::xml_node& _node) { + const auto lang_attr = _node.attribute("lang"); + if (!lang_attr) { + return rfl::error("RichText node missing 'lang' attribute."); + } + RichText out; + out.lang = lang_attr.value(); + for (auto child = _node.first_child(); child; + child = child.next_sibling()) { + if (child.type() == pugi::node_pcdata) { + out.plain += child.value(); + } else if (child.type() == pugi::node_element && + std::string_view(child.name()) == "b") { + out.plain += child.child_value(); + out.bold_spans.emplace_back(child.child_value()); + } + } + return out; + } +}; + +struct Article { + std::string title; + RichText body; +}; + +struct DirectValueNode { + std::string text; + + static DirectValueNode from_xml_node(const pugi::xml_node& _node) { + return DirectValueNode{.text = std::string(_node.child_value())}; + } +}; + +struct ThrowingNode { + int v = 0; + + static ThrowingNode from_xml_node(const pugi::xml_node&) { + throw std::runtime_error("custom parse failure"); + } +}; + +struct MoveOnlyNode { + std::unique_ptr value; + + static rfl::Result from_xml_node(const pugi::xml_node& _node) { + return MoveOnlyNode{.value = std::make_unique(_node.text().as_int())}; + } +}; + +TEST(xml_pugixml_interop, custom_from_xml_node_in_reflected_struct) { + const char* xml = R"( +
+ Hello + Click here or there! +
+)"; + + const auto res = rfl::xml::read
(xml); + ASSERT_TRUE(res) << res.error().what(); + EXPECT_EQ(res.value().title, "Hello"); + EXPECT_EQ(res.value().body.lang, "en"); + EXPECT_EQ(res.value().body.plain, "Click here or there!"); + ASSERT_EQ(res.value().body.bold_spans.size(), 2u); + EXPECT_EQ(res.value().body.bold_spans[0], "here"); + EXPECT_EQ(res.value().body.bold_spans[1], "there"); + + // Error returned by from_xml_node propagates cleanly. + const auto missing_attr = + rfl::xml::read
("
Thi
"); + EXPECT_FALSE(missing_attr); + + // Attribute matched against a from_xml_node field returns an error cleanly. + const auto attr_instead_of_elem = + rfl::xml::read
("
T
"); + EXPECT_FALSE(attr_instead_of_elem); + + // Direct value return (non-Result), exception catching, and move-only types. + const auto direct = + rfl::xml::read("abc"); + ASSERT_TRUE(direct) << direct.error().what(); + EXPECT_EQ(direct.value().text, "abc"); + + const auto thrown = + rfl::xml::read("1"); + ASSERT_FALSE(thrown); + EXPECT_NE(thrown.error().what().find("custom parse failure"), + std::string::npos); + + const auto move_only = + rfl::xml::read("99"); + ASSERT_TRUE(move_only) << move_only.error().what(); + ASSERT_NE(move_only.value().value, nullptr); + EXPECT_EQ(*move_only.value().value, 99); +} + +TEST(xml_pugixml_interop, regression_get_field_from_array) { + pugi::xml_document doc; + ASSERT_TRUE(doc.load_string( + "102030")); + + const rfl::xml::Reader reader; + const rfl::xml::Reader::InputArrayType arr(doc.child("root").child("v")); + + const auto elem0 = reader.get_field_from_array(0, arr); + ASSERT_TRUE(elem0) << elem0.error().what(); + EXPECT_EQ(reader.to_basic_type(elem0.value()).value(), 10); + + const auto elem1 = reader.get_field_from_array(1, arr); + ASSERT_TRUE(elem1) << elem1.error().what(); + EXPECT_EQ(reader.to_basic_type(elem1.value()).value(), 20); + + const auto elem2 = reader.get_field_from_array(2, arr); + ASSERT_TRUE(elem2) << elem2.error().what(); + EXPECT_EQ(reader.to_basic_type(elem2.value()).value(), 30); + + const auto oob = reader.get_field_from_array(3, arr); + EXPECT_FALSE(oob); + + // Also verify std::tuple and std::array round-trip cleanly in XML. + struct WithSeq { + std::tuple tup; + std::array arr; + }; + const WithSeq orig{.tup = {1, "two", true}, .arr = {4, 5, 6}}; + const auto xml = rfl::xml::write(orig); + const auto parsed = rfl::xml::read(xml); + ASSERT_TRUE(parsed) << parsed.error().what(); + EXPECT_EQ(parsed.value().tup, orig.tup); + EXPECT_EQ(parsed.value().arr, orig.arr); +} + +TEST(xml_pugixml_interop, regression_write_custom_indent) { + struct Simple { + int a = 1; + std::string b = "two"; + }; + + const Simple s; + const auto indent2 = rfl::xml::write(s, " "); + EXPECT_EQ(indent2, + "\n" + "\n" + " 1\n" + " two\n" + "\n"); + + const auto indent_tab = rfl::xml::write(s, "\t"); + EXPECT_EQ(indent_tab, + "\n" + "\n" + "\t1\n" + "\ttwo\n" + "\n"); +} + +} // namespace test_pugixml_interop From f1e08171dc206a143a35a0bcdaafd9d66c615ba6 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 09:16:46 +0100 Subject: [PATCH 2/2] Address review feedback: rename from_xml_obj, drop redundant xml_document overload, guard empty root name, add docs --- docs/content/supported_formats/xml.md | 32 +++++++++++++++++++++++++++ include/rfl/xml/Reader.hpp | 10 ++++----- include/rfl/xml/read.hpp | 22 ++++-------------- include/rfl/xml/write.hpp | 7 +++--- tests/xml/test_pugixml_interop.cpp | 17 +++++++------- 5 files changed, 54 insertions(+), 34 deletions(-) diff --git a/docs/content/supported_formats/xml.md b/docs/content/supported_formats/xml.md index a28cf95f9..6d5405f97 100644 --- a/docs/content/supported_formats/xml.md +++ b/docs/content/supported_formats/xml.md @@ -252,3 +252,35 @@ const auto person = Person{...}; rfl::xml::save("/path/to/file.xml", person); ``` +## Interoperating directly with `pugixml` + +You can combine `pugixml` DOM / XPath navigation with `reflect-cpp` on clean subtrees: + +```cpp +pugi::xml_document doc; +doc.load_file("project.xml"); + +// Read a reflected struct directly from a pugi::xml_node (or pugi::xml_document): +const auto node = doc.select_node("//settings/compiler").node(); +const auto cfg = rfl::xml::read(node).value(); + +// Splice a reflected struct under an existing parent node without disturbing siblings: +const pugi::xml_node appended = rfl::xml::write<"compiler">(cfg, target_parent); +// Or with a runtime element name (returns an empty node if parent or name is empty): +const pugi::xml_node dynamic = rfl::xml::write(cfg, target_parent, "compiler"); +``` + +For individual fields with mixed content, XML namespaces, or custom XPath logic, +provide a static `from_xml_obj(const pugi::xml_node&)` method returning `T` or +`rfl::Result`: + +```cpp +struct RichText { + std::string raw_text; + + static rfl::Result from_xml_obj(const pugi::xml_node& _node) { + return RichText{_node.text().as_string()}; + } +}; +``` + diff --git a/include/rfl/xml/Reader.hpp b/include/rfl/xml/Reader.hpp index 1d85e5b9d..667e9d098 100644 --- a/include/rfl/xml/Reader.hpp +++ b/include/rfl/xml/Reader.hpp @@ -52,12 +52,12 @@ struct Reader { using InputVarType = XMLInputVar; /// Compile-time flag indicating whether type T has a custom constructor from XML. - /// If true, the type provides a static from_xml_node(const pugi::xml_node&) + /// If true, the type provides a static from_xml_obj(const pugi::xml_node&) /// method returning T or rfl::Result for custom deserialization. template static constexpr bool has_custom_constructor = (requires(const pugi::xml_node& node) { - { T::from_xml_node(node) } -> std::convertible_to>; + { T::from_xml_obj(node) } -> std::convertible_to>; }); /// Retrieves an element from an XML array by index. @@ -224,8 +224,8 @@ struct Reader { } /// Uses a type's custom constructor to deserialize from an XML node. - /// Calls the type's static from_xml_node(const pugi::xml_node&) method. - /// @tparam T The type to construct, must have a from_xml_node() static method + /// Calls the type's static from_xml_obj(const pugi::xml_node&) method. + /// @tparam T The type to construct, must have a from_xml_obj() static method /// @param _var The XML value to deserialize from (must be a node, not an attribute) /// @return Result containing the constructed object, or an error if construction fails template @@ -233,7 +233,7 @@ struct Reader { const InputVarType _var) const noexcept { const auto call_ctor = [](const pugi::xml_node& _node) -> rfl::Result { try { - return T::from_xml_node(_node); + return T::from_xml_obj(_node); } catch (const std::exception& e) { return error(e.what()); } diff --git a/include/rfl/xml/read.hpp b/include/rfl/xml/read.hpp index 247355b10..da9e62933 100644 --- a/include/rfl/xml/read.hpp +++ b/include/rfl/xml/read.hpp @@ -33,11 +33,12 @@ auto read(const InputVarType& _var) { return Parser::read(r, _var); } -/// Parses an object from a pugixml node (subtree). -/// If the node is a document node, its root element is parsed. +/// Parses an object from a pugixml node (or `pugi::xml_document`, which derives +/// from `pugi::xml_node`). If the node is a document node, its root element is +/// parsed (skipping declarations, comments, etc.). /// @tparam T The type to parse into /// @tparam Ps Processors to apply during parsing (transforms the data) -/// @param _node The pugixml node to parse from +/// @param _node The pugixml node or document to parse from /// @return Result containing either the parsed object of type T or an error message template Result read(const pugi::xml_node& _node) { @@ -56,21 +57,6 @@ Result read(const pugi::xml_node& _node) { return read(InputVarType(_node)); } -/// Parses an object from a pugixml document. -/// Parses the document's root element (skipping declarations, comments, etc.). -/// @tparam T The type to parse into -/// @tparam Ps Processors to apply during parsing (transforms the data) -/// @param _doc The pugixml document to parse from -/// @return Result containing either the parsed object of type T or an error message -template -Result read(const pugi::xml_document& _doc) { - const auto root = _doc.document_element(); - if (!root) { - return error("XML document has no root element."); - } - return read(InputVarType(root)); -} - /// Parses an object from XML using reflection. /// This function reads an XML string and constructs a C++ object using compile-time reflection. /// @tparam T The type to parse into diff --git a/include/rfl/xml/write.hpp b/include/rfl/xml/write.hpp index 34d42cc3f..be540c631 100644 --- a/include/rfl/xml/write.hpp +++ b/include/rfl/xml/write.hpp @@ -39,12 +39,13 @@ consteval auto get_root_name() { /// @tparam Ps Processors to apply during serialization (transforms the data) /// @param _obj The object to serialize to XML /// @param _parent The parent pugixml node (or document) to append under -/// @param _root_name The name of the appended child element -/// @return The newly appended pugixml node (or an empty node if `_parent` is empty) +/// @param _root_name The name of the appended child element (must be non-empty) +/// @return The newly appended pugixml node, or an empty node if `_parent` is +/// empty or `_root_name` is empty template pugi::xml_node write(const auto& _obj, pugi::xml_node _parent, const std::string& _root_name) { - if (!_parent) { + if (!_parent || _root_name.empty()) { return pugi::xml_node(); } using T = std::remove_cvref_t; diff --git a/tests/xml/test_pugixml_interop.cpp b/tests/xml/test_pugixml_interop.cpp index fd66af8e7..f093b0977 100644 --- a/tests/xml/test_pugixml_interop.cpp +++ b/tests/xml/test_pugixml_interop.cpp @@ -154,8 +154,9 @@ TEST(xml_pugixml_interop, write_splice_into_existing_node) { EXPECT_EQ(root, standalone.document_element()); EXPECT_EQ(rfl::xml::read(standalone).value().item_name, "Sprocket"); - // Writing into an empty handle fails safely by returning an empty node. + // Writing into an empty handle or with an empty runtime root name fails safely. EXPECT_FALSE(rfl::xml::write(item, pugi::xml_node{})); + EXPECT_FALSE(rfl::xml::write(item, config, "")); } struct RichText { @@ -163,7 +164,7 @@ struct RichText { std::string plain; std::vector bold_spans; - static rfl::Result from_xml_node(const pugi::xml_node& _node) { + static rfl::Result from_xml_obj(const pugi::xml_node& _node) { const auto lang_attr = _node.attribute("lang"); if (!lang_attr) { return rfl::error("RichText node missing 'lang' attribute."); @@ -192,7 +193,7 @@ struct Article { struct DirectValueNode { std::string text; - static DirectValueNode from_xml_node(const pugi::xml_node& _node) { + static DirectValueNode from_xml_obj(const pugi::xml_node& _node) { return DirectValueNode{.text = std::string(_node.child_value())}; } }; @@ -200,7 +201,7 @@ struct DirectValueNode { struct ThrowingNode { int v = 0; - static ThrowingNode from_xml_node(const pugi::xml_node&) { + static ThrowingNode from_xml_obj(const pugi::xml_node&) { throw std::runtime_error("custom parse failure"); } }; @@ -208,12 +209,12 @@ struct ThrowingNode { struct MoveOnlyNode { std::unique_ptr value; - static rfl::Result from_xml_node(const pugi::xml_node& _node) { + static rfl::Result from_xml_obj(const pugi::xml_node& _node) { return MoveOnlyNode{.value = std::make_unique(_node.text().as_int())}; } }; -TEST(xml_pugixml_interop, custom_from_xml_node_in_reflected_struct) { +TEST(xml_pugixml_interop, custom_from_xml_obj_in_reflected_struct) { const char* xml = R"(
Hello @@ -230,12 +231,12 @@ TEST(xml_pugixml_interop, custom_from_xml_node_in_reflected_struct) { EXPECT_EQ(res.value().body.bold_spans[0], "here"); EXPECT_EQ(res.value().body.bold_spans[1], "there"); - // Error returned by from_xml_node propagates cleanly. + // Error returned by from_xml_obj propagates cleanly. const auto missing_attr = rfl::xml::read
("
Thi
"); EXPECT_FALSE(missing_attr); - // Attribute matched against a from_xml_node field returns an error cleanly. + // Attribute matched against a from_xml_obj field returns an error cleanly. const auto attr_instead_of_elem = rfl::xml::read
("
T
"); EXPECT_FALSE(attr_instead_of_elem);