3 #include "xml-writer.hh"
9 XMLWriter::XMLWriter(bool indent
, std::ostream
& output
)
10 : output(output
), indent(indent
)
12 output
<< "<?xml version='1.0' encoding='utf-8'?>" << std::endl
;
17 XMLWriter::~XMLWriter()
23 void XMLWriter::close()
26 while (!pendingElems
.empty()) closeElement();
31 void XMLWriter::indent_(unsigned int depth
)
34 output
<< string(depth
* 2, ' ');
38 void XMLWriter::openElement(const string
& name
,
39 const XMLAttrs
& attrs
)
42 indent_(pendingElems
.size());
43 output
<< "<" << name
;
46 if (indent
) output
<< std::endl
;
47 pendingElems
.push_back(name
);
51 void XMLWriter::closeElement()
53 assert(!pendingElems
.empty());
54 indent_(pendingElems
.size() - 1);
55 output
<< "</" << pendingElems
.back() << ">";
56 if (indent
) output
<< std::endl
;
57 pendingElems
.pop_back();
58 if (pendingElems
.empty()) closed
= true;
62 void XMLWriter::writeEmptyElement(const string
& name
,
63 const XMLAttrs
& attrs
)
66 indent_(pendingElems
.size());
67 output
<< "<" << name
;
70 if (indent
) output
<< std::endl
;
74 void XMLWriter::writeAttrs(const XMLAttrs
& attrs
)
76 for (XMLAttrs::const_iterator i
= attrs
.begin(); i
!= attrs
.end(); ++i
) {
77 output
<< " " << i
->first
<< "=\"";
78 for (unsigned int j
= 0; j
< i
->second
.size(); ++j
) {
79 char c
= i
->second
[j
];
80 if (c
== '"') output
<< """;
81 else if (c
== '<') output
<< "<";
82 else if (c
== '>') output
<< ">";
83 else if (c
== '&') output
<< "&";
84 /* Escape newlines to prevent attribute normalisation (see
85 XML spec, section 3.3.3. */
86 else if (c
== '\n') output
<< "
";