Click here to Skip to main content
Click here to Skip to main content

Simple C++ class for XML writing

By , 4 Dec 2003
 

Introduction

In some of my programs, I have to write the data in XML format. Only writing: reading and parsing is the mission of some other tools. Actually I only have to write the simple plain text with some specific markup.

For these purposes, I have implemented a simple class, which behaves as usual std::stream, but also track all the needed XML markings. The class implementation is very simple and template-based. One may write to XmlStream, everything that can be written into std::ostream. The tags and attributes are declared by special helper functions.

Using the code

Look at the example below, which tells everything about my class (I specially omitted the implementation of the XmlStream class, if you’ve interest in it, you'll download the source code, I think).

ofstream f("sample.xml");
XmlStream xml(f);

xml << prolog() // write XML file declaration
  << tag("sample-tag") // root tag

    << tag("some-tag") // child tag
      << attr("int-attribute") << 123
      << attr("double-attribute") << 456.789
      << chardata() << "This is the text"
    << endtag() // close current tag

    << tag("empty-self-closed-tag") // sibling of <some-tag>
    << endtag()

    << tag() << "computed-name-tag"
      << attr("text-attr") << "a bit of text"
    << endtag()

    << tag("deep-tag") // deep enclosing
      << tag("sub-tag-2")
        << tag("sub-tag-3")
    << endtag("deep-tag"); // close all tags up to specified

// you don't worry about closing all open tags!

As you can see, writing of XML became a very simple procedure. XmlStream delegates all the incoming data to a specified std::ostream (std::ofstream in the example above) except for the tags and attributes declarations, which are issued by helper functions: tag(), endtag(), attr(), chardata() and prolog(). To fill attribute values and tag character data, one should use standard stream operations. If object of some class can be written into std::ostream, it's automatically writeable into my XmlStream. This feature is released by template operator<<, which mostly calls standard streaming operations.

template<class t> XmlStream& operator<<(const t& value) {
  // for computed-name tags we have to remember written data
  if (stateTagName == state)
    // tagName is object of std::ostringstream class
    tagName << value;
  // now call specified std::stream which
  // performs actual output  
  s << value;
  return *this;
}

The final executable contains only those implementations of this operator, which corresponds to actually used data types.

Advantages of my approach

  • Writing of XML data is very fast (almost as fast as plain text writing).
  • You use standard and well-known functions to build the content of the XML document. It's simple to implement new operator's supporting any user classes.
  • The source code, which writes XML data, represents itself the structure of the resulting document.
  • XmlStream is a really tiny class! Almost all of its work is placed in one overloaded operator<<.

Disadvantages

  • All the data are written into XML "as is", without any encoding (UTF-8, UTF-16 etc.). In my tasks, it's often not a matter of headache, because my data are simply either Latin alphas or numbers. But for the common case, one may have to implement special std::ostream (in fact: std::streambuf) successor, which will perform the encoding work.
  • XmlStream does not check if output XML data represent well-formed XML document. Programmer must check himself whether the tag and attribute names are valid and there are no special characters (like angle brackets) in the attribute values and character data.

Futures

The current version of XmlWriter is used in my programs, which outputs the results of the scientific calculations in XML format. If someone wants to improve this simple class, he may first get rid of disadvantages mentioned above. Also he might change the processing of the tags to make output XML documents more human-readable (i.e. add line separators, padding etc).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Oboltus
Web Developer
Russian Federation Russian Federation
Member
Programming since 1992
Favorite programming language: C++
Main interest (currently): computer modeling of physical processes in radiation-damaged metalls

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questioncant find .exe in xml writingmemberyidiiss8 Nov '11 - 6:35 
GeneralGood, waiting for the opposite directionmemberCPallini8 Nov '07 - 21:16 
GeneralRe: Good, waiting for the opposite directionmemberyidiiss8 Nov '11 - 6:42 
GeneralRe: Good, waiting for the opposite directionmemberyidiiss8 Nov '11 - 6:42 
GeneralLove the code - here's a tiny readability mod [modified]memberalan.witmer10 Oct '07 - 3:31 
QuestionAppend tag into xml:memberchuansiong4 Oct '07 - 1:14 
QuestionIn unixmemberSinthiya Marian9 Feb '07 - 23:16 
Generalreader xml in c++memberDang Viet Dat23 Dec '06 - 2:10 
GeneralWoW!!!!!!!!membershahsani8345 Nov '06 - 14:04 
GeneralloadLibrary errormemberRadia624 May '06 - 16:50 
i had a LoadLibrary error when i apply this code in my project. The error is:
 
LoadLibrary error( e=7 specified module could not be found)
 
I need some help
 
thank you
Generalxmlwriter detailsmemberBernd Speiser11 Sep '05 - 7:16 
QuestionUnicode?memberAbu Mami11 Mar '05 - 1:40 
GeneralUse conditionsmemberdmaximov22 Apr '04 - 21:48 
GeneralRe: Use conditionsmemberOboltus26 Apr '04 - 23:05 
GeneralRe: Use conditionsmemberdmaximov27 Apr '04 - 18:29 
Generalread XMLmemberblablakam28 Jan '04 - 4:41 
GeneralRead XML!memberM.Khadem18 Dec '03 - 0:59 
GeneralXML ReadermemberNagesh P10 Dec '03 - 23:49 
GeneralRe: XML ReadermemberOboltus11 Dec '03 - 0:02 
GeneralMicrosoft XMLDOM interfacememberNadiaTariq10 Dec '03 - 1:02 
GeneralRe: Microsoft XMLDOM interfacememberOboltus10 Dec '03 - 9:01 
GeneralRe: Microsoft XMLDOM interfacememberVince C.10 Dec '03 - 10:13 
GeneralSimplest is usually the best...memberVince C.9 Dec '03 - 23:15 
GeneralRe: Simplest is usually the best...memberOboltus10 Dec '03 - 9:02 
GeneralRe: Simplest is usually the best...memberMai-K15 Dec '05 - 9:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 5 Dec 2003
Article Copyright 2003 by Oboltus
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid