Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions docs/content/supported_formats/xml.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<CompilerConfig>(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<T>`:

```cpp
struct RichText {
std::string raw_text;

static rfl::Result<RichText> from_xml_obj(const pugi::xml_node& _node) {
return RichText{_node.text().as_string()};
}
};
```

32 changes: 22 additions & 10 deletions include/rfl/xml/Reader.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define RFL_XML_READER_HPP_

#include <charconv>
#include <concepts>
#include <exception>
#include <optional>
#include <pugixml.hpp>
Expand Down Expand Up @@ -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_obj(const pugi::xml_node&)
/// method returning T or rfl::Result<T> for custom deserialization.
template <class T>
static constexpr bool has_custom_constructor = false;
static constexpr bool has_custom_constructor =
(requires(const pugi::xml_node& node) {
{ T::from_xml_obj(node) } -> std::convertible_to<rfl::Result<T>>;
});

/// Retrieves an element from an XML array by index.
/// In XML, arrays are represented as sibling elements with the same name.
Expand All @@ -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.
Expand Down Expand Up @@ -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_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 <class T>
rfl::Result<T> use_custom_constructor(
const InputVarType _var) const noexcept {
return error("TODO");
const auto call_ctor = [](const pugi::xml_node& _node) -> rfl::Result<T> {
try {
return T::from_xml_obj(_node);
} catch (const std::exception& e) {
return error(e.what());
}
};
return cast_as_node(_var.node_or_attribute_).and_then(call_ctor);
}

private:
Expand Down
27 changes: 25 additions & 2 deletions include/rfl/xml/read.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,30 @@ auto read(const InputVarType& _var) {
return Parser<T, ProcessorsType>::read(r, _var);
}

/// 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 or document to parse from
/// @return Result containing either the parsed object of type T or an error message
template <class T, class... Ps>
Result<T> 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<T, Ps...>(InputVarType(child));
}
}
return error("XML document has no root element.");
}
return read<T, Ps...>(InputVarType(_node));
}

/// 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
Expand All @@ -47,8 +71,7 @@ Result<T> 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<T, Ps...>(var);
return read<T, Ps...>(doc);
}

/// Parses an object from a stringstream containing XML.
Expand Down
75 changes: 56 additions & 19 deletions include/rfl/xml/write.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -33,20 +33,48 @@ 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 (must be non-empty)
/// @return The newly appended pugixml node, or an empty node if `_parent` is
/// empty or `_root_name` is empty
template <class... Ps>
pugi::xml_node write(const auto& _obj, pugi::xml_node _parent,
const std::string& _root_name) {
if (!_parent || _root_name.empty()) {
return pugi::xml_node();
}
using T = std::remove_cvref_t<decltype(_obj)>;
using ParentType = parsing::Parent<Writer>;

const auto prev_last = _parent.last_child();
const auto parent_ref = Ref<pugi::xml_node>::make(_parent);
auto w = Writer(parent_ref, _root_name);

using ProcessorsType = Processors<Ps...>;
static_assert(!internal::no_field_names_v<ProcessorsType>,
"The NoFieldNames processor is not supported for BSON, XML, "
"TOML, or YAML.");
Parser<T, ProcessorsType>::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 <internal::StringLiteral _root = internal::StringLiteral(""),
class... Ps>
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<decltype(_obj)>;
using ParentType = parsing::Parent<Writer>;

constexpr auto root_name = get_root_name<_root, T>();

Expand All @@ -57,21 +85,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<pugi::xml_document>::make();
return write<Ps...>(_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 <internal::StringLiteral _root = internal::StringLiteral(""),
class... Ps>
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<Ps...>;
static_assert(!internal::no_field_names_v<ProcessorsType>,
"The NoFieldNames processor is not supported for BSON, XML, "
"TOML, or YAML.");
Parser<T, ProcessorsType>::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;
}
Expand All @@ -87,7 +124,7 @@ template <internal::StringLiteral _root = internal::StringLiteral(""),
class... Ps>
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();
}

Expand Down
Loading