97e43445af0ae57fa120f997662828cee79d9af8
[supertux.git] / tools / miniswig / xmlwriter.hpp
1 #ifndef __XMLWRITER_H__
2 #define __XMLWRITER_H__
3
4 #include <iostream>
5 #include <vector>
6 #include <string>
7
8 /** This class is a class which helps printing formated xml output.
9  * Example:
10  *  This sequence:
11  *   xml.openTag("world");
12  *   xml.writeAttribute("name", "foo");
13  *   xml.writeTag("bar");
14  *   xml.writeTag("baz");
15  *   xml.writeAttribute("name", "boo");
16  *   xml.writeAttribute("style", "old");
17  *   xml.write("text");
18  *   xml.closeTag("world");
19  *  results in this output:
20  *   <world name="foo">
21  *     <bar/>
22  *     <baz name="boo" style="old">text</baz>
23  *   </world>
24  */
25 class XmlWriter {
26 public:
27     XmlWriter(std::ostream& out);
28     ~XmlWriter();
29    
30     /** Start a xml tag which contains subtags */
31     void openTag(const char* name);
32     /** Closes an xml tag with subtags */
33     void closeTag(const char* name);
34
35     void writeTag(const char* name);
36
37     template <class T> 
38       void comment(const T& outp)
39       {   // This routine writes just about anything as an XML comment.
40         newLine();
41         out << "<!-- " << outp ;
42         closetag = " -->";
43       }
44
45
46     template<class T>
47     void write(const T& text)
48     {
49         if (closetag[0]=='>') {
50             out << ">";
51             closetag = "";
52         } else if (closetag[0]=='/') {
53             out << ">"; // eventually we should place a \n here
54             closetag = "</";
55             closetag += lasttag;
56             closetag += ">";
57         }
58         out << text;
59     }
60
61     template<class T>
62     void writeAttribute(const char* name, T value)
63     {
64         out << " " << name << "=\"" << value << "\"";
65     }
66
67 private:
68     void newLine();
69     void closeTag();
70     
71     std::ostream& out;
72     int indent;
73     std::string closetag;
74     std::string lasttag;
75     std::vector<std::string> sections;
76 };
77
78 #endif
79