contrib/brl/bbas/bxml/bxml_write.cxx
Go to the documentation of this file.
00001 // This is brl/bbas/bxml/bxml_write.cxx
00002 #ifdef VCL_NEEDS_PRAGMA_INTERFACE
00003 #pragma implementation
00004 #endif
00005 //:
00006 // \file
00007 // \author Matt Leotta
00008 // \date   October 5, 2006
00009 
00010 #include "bxml_write.h"
00011 #include <vcl_fstream.h>
00012 
00013 
00014 //: Write the entire contents of \p filepath into an XML document class
00015 void bxml_write(const vcl_string& filepath, const bxml_document& doc)
00016 {
00017   vcl_ofstream file(filepath.c_str());
00018   bxml_write(file, doc);
00019 }
00020 
00021 
00022 //: Write the entire data stream \p is into an XML document class
00023 void bxml_write(vcl_ostream& os, const bxml_document& doc)
00024 {
00025   bxml_write_declaration(os, doc);
00026   bxml_write_data(os, doc.root_element());
00027 }
00028 
00029 
00030 //: Write the document declaration (header)
00031 void bxml_write_declaration(vcl_ostream& os, const bxml_document& doc)
00032 {
00033   os  << "<?xml version=\"" << doc.version() << '"'
00034       << " encoding=\"" << doc.encoding() << '"'
00035       << " standalone=\"" << (doc.standalone() ? "yes" : "no") << "\"?>\n";
00036 }
00037 
00038 
00039 //: Write the data (element or text)
00040 void bxml_write_data(vcl_ostream& os, const bxml_data_sptr& data)
00041 {
00042   if (!data)
00043     return;
00044 
00045   if (data->type() == bxml_data::TEXT) {
00046     bxml_text* text = static_cast<bxml_text*>(data.ptr());
00047     os << text->data();
00048   }
00049 
00050   if (data->type() == bxml_data::ELEMENT) {
00051     bxml_element* element = static_cast<bxml_element*>(data.ptr());
00052     bxml_write_element(os, *element);
00053   }
00054 }
00055 
00056 
00057 //: Write the XML element
00058 void bxml_write_element(vcl_ostream& os, const bxml_element& element)
00059 {
00060   // open the start tag
00061   os << '<' << element.name();
00062 
00063   // write the attributes
00064   for (bxml_element::const_attr_iterator i = element.attr_begin();
00065        i != element.attr_end();  ++i)
00066   {
00067     os << ' '<<i->first<<"=\""<<i->second<<'"';
00068   }
00069 
00070   // check if this should be an empty tag
00071   if (element.data_begin() == element.data_end()) {
00072     os << " />";
00073     return;
00074   }
00075   os << '>';
00076 
00077   // write the data within the tag
00078   for (bxml_element::const_data_iterator i = element.data_begin();
00079        i != element.data_end();  ++i)
00080   {
00081     bxml_write_data(os, *i);
00082   }
00083 
00084   // end tag
00085   os << "</" << element.name() << '>';
00086 }