draconisplusplus/include/rfl/xml/write.hpp

74 lines
2.3 KiB
C++
Raw Normal View History

2024-06-05 19:04:53 -04:00
#ifndef RFL_XML_WRITE_HPP_
#define RFL_XML_WRITE_HPP_
#include <ostream>
#include <pugixml.hpp>
#include <sstream>
#include <string>
#include <type_traits>
#include "../Processors.hpp"
#include "../internal/StringLiteral.hpp"
#include "../internal/get_type_name.hpp"
#include "../internal/remove_namespaces.hpp"
#include "../parsing/Parent.hpp"
#include "Parser.hpp"
namespace rfl {
2024-06-08 14:10:59 -04:00
namespace xml {
template <internal::StringLiteral _root, class T>
consteval auto get_root_name() {
if constexpr (_root != internal::StringLiteral("")) {
return _root;
} else {
2024-06-16 00:13:15 -04:00
return internal::remove_namespaces<internal::get_type_name<std::remove_cvref_t<T>>()>();
2024-06-08 14:10:59 -04:00
}
}
/// Writes a XML into an ostream.
2024-06-16 00:13:15 -04:00
template <internal::StringLiteral _root = internal::StringLiteral(""), class... Ps>
std::ostream&
write(const auto& _obj, std::ostream& _stream, const std::string& _indent = " ") {
2024-06-08 14:10:59 -04:00
using T = std::remove_cvref_t<decltype(_obj)>;
using ParentType = parsing::Parent<Writer>;
constexpr auto root_name = get_root_name<_root, T>();
static_assert(
2024-06-16 00:13:15 -04:00
root_name.string_view().find("<") == std::string_view::npos &&
root_name.string_view().find(">") == std::string_view::npos,
"The name of an XML root node cannot contain '<' or '>'. "
"Please assign an "
"explicit root name to rfl::xml::write(...) like this: "
"rfl::xml::write<\"root_name\">(...)."
2024-06-08 15:53:06 -04:00
);
2024-06-08 14:10:59 -04:00
const auto doc = rfl::Ref<pugi::xml_document>::make();
2024-06-16 00:13:15 -04:00
auto declaration_node = doc->append_child(pugi::node_declaration);
2024-06-08 14:10:59 -04:00
declaration_node.append_attribute("version") = "1.0";
declaration_node.append_attribute("encoding") = "UTF-8";
auto w = Writer(doc, root_name.str());
2024-06-16 00:13:15 -04:00
Parser<T, Processors<Ps...>>::write(w, _obj, typename ParentType::Root {});
2024-06-08 14:10:59 -04:00
doc->save(_stream, _indent.c_str());
return _stream;
}
/// Returns a XML string.
2024-06-16 00:13:15 -04:00
template <internal::StringLiteral _root = internal::StringLiteral(""), class... Ps>
2024-06-08 14:10:59 -04:00
std::string write(const auto& _obj, const std::string& _indent = " ") {
std::stringstream stream;
write<_root, Ps...>(_obj, stream);
return stream.str();
}
} // namespace xml
} // namespace rfl
#endif // XML_PARSER_HPP_