Simple XML outputter

If you have a cool piece of software to share, but you are not hosting it officially yet, please dump it in here. If you have code snippets that are useful, please donate!
Post Reply
ssigala
Earned some good credits
Earned some good credits
Posts: 109
Joined: Fri Sep 03, 2004 9:30 am
Location: Brescia, Italy

Simple XML outputter

Post by ssigala » Mon Aug 22, 2005 3:27 pm

This class simplifies the work when generating XML documents: no more need to take care of XML indentation and closing the right section.

Example of application:

Code: Select all

wxFileOutputStream stream("test.xml");

XMLOutput xmlout(stream);
xmlout.OpenSection("document");

xmlout.OpenSection("info");
xmlout.OpenSection("items");

xmlout.WriteItem("<foo x=\"1\" />");
xmlout.WriteItem("<foo x=\"2\" />");
xmlout.WriteItem("<foo x=\"3\" />");

xmlout.CloseSection(); // items
xmlout.CloseSection(); // info

xmlout.CloseSection(); // document

stream.Close();
Generates the following file:

Code: Select all

<?xml version="1.0" standalone="no"?>
<document>
    <info>
        <items>
            <foo x="1" />
            <foo x="2" />
            <foo x="3" />
        </items>
    </info>
</document>

Code: Select all

class XMLOutput {
public:
	XMLOutput(wxOutputStream& stream) : m_stream(stream), m_text(stream) {
		m_depth = 0;
		m_text.SetMode(wxEOL_UNIX);
		m_text << "<?xml version=\"1.0\" standalone=\"no\"?>\n";
	}
	~XMLOutput() { wxASSERT(m_depth == 0); }

	void OpenSection(const wxString& section) {
		m_sections.Add(section);
		Indent();
		m_text << "<" << section << ">\n";
		++m_depth;
	}
	void CloseSection() {
		wxString section = m_sections.Last();
		m_sections.RemoveAt(m_sections.GetCount() - 1);
		--m_depth;
		Indent();
		m_text << "</" << section << ">\n";
	}
	void WriteItem(const wxString& item) {
		Indent();
		m_text << item << '\n';
	}

private:
	wxOutputStream& m_stream;
	wxTextOutputStream m_text;
	int m_depth;
	wxArrayString m_sections;

	void Indent() {
		for (int i = 0; i < m_depth; ++i)
			m_text << "    ";
	}
};
Sandro Sigala - Kynosoft, Brescia

daddydave
Filthy Rich wx Solver
Filthy Rich wx Solver
Posts: 214
Joined: Wed Jun 15, 2005 3:31 am
Location: United States
Contact:

Post by daddydave » Mon Aug 22, 2005 3:57 pm

Fantastic!

Jorg
Moderator
Moderator
Posts: 3971
Joined: Fri Aug 27, 2004 9:38 pm
Location: Delft, Netherlands
Contact:

Post by Jorg » Tue Aug 23, 2005 6:50 am

Very slick! :-)
- Jorgen
Forensic Software Engineer
Netherlands Forensic Insitute
http://english.forensischinstituut.nl/
-------------------------------------
Jorg's WasteBucket
http://www.xs4all.nl/~jorgb/wb

Post Reply