Loading...
Searching...
No Matches
xml.hpp
Go to the documentation of this file.
1
2
3#pragma once
4
5#include <map>
6#include <sstream>
7#include <string>
8#include <utility>
9#include <vector>
10
11namespace terra::util {
12
13class XML
14{
15 public:
16 explicit XML(
17 std::string name,
18 const std::map< std::string, std::string >& attributes = {},
19 std::string content = "" )
20 : name_( std::move( name ) )
21 , content_( std::move( content ) )
22 {
23 attributes_.insert( attributes.begin(), attributes.end() );
24 }
25
26 XML& add_child( const XML& child )
27 {
28 children_.push_back( child );
29 return *this;
30 }
31
32 [[nodiscard]] std::string to_string() const { return to_string( 0 ); }
33
34 private:
35 std::string name_;
36 std::string content_;
37 std::vector< XML > children_;
38 std::map< std::string, std::string > attributes_;
39
40 [[nodiscard]] std::string to_string( int indent ) const
41 {
42 std::ostringstream oss;
43 std::string indent_str( indent, ' ' );
44
45 oss << indent_str << "<" << name_;
46 for ( const auto& attr : attributes_ )
47 {
48 oss << " " << attr.first << "=\"" << escape_xml( attr.second ) << "\"";
49 }
50
51 if ( children_.empty() && content_.empty() )
52 {
53 oss << " />\n";
54 }
55 else
56 {
57 oss << ">";
58 if ( !content_.empty() )
59 {
60 oss << escape_xml( content_ );
61 }
62 if ( !children_.empty() )
63 {
64 oss << "\n";
65 for ( const auto& child : children_ )
66 {
67 oss << child.to_string( indent + 2 );
68 }
69 oss << indent_str;
70 }
71 oss << "</" << name_ << ">\n";
72 }
73
74 return oss.str();
75 }
76
77 static std::string escape_xml( const std::string& data )
78 {
79 std::ostringstream escaped;
80 for ( char c : data )
81 {
82 switch ( c )
83 {
84 case '&':
85 escaped << "&amp;";
86 break;
87 case '\"':
88 escaped << "&quot;";
89 break;
90 case '\'':
91 escaped << "&apos;";
92 break;
93 case '<':
94 escaped << "&lt;";
95 break;
96 case '>':
97 escaped << "&gt;";
98 break;
99 default:
100 escaped << c;
101 break;
102 }
103 }
104 return escaped.str();
105 }
106};
107
108} // namespace terra::util
Definition xml.hpp:14
std::string to_string() const
Definition xml.hpp:32
XML(std::string name, const std::map< std::string, std::string > &attributes={}, std::string content="")
Definition xml.hpp:16
XML & add_child(const XML &child)
Definition xml.hpp:26
Definition solver.hpp:9