Skip to main content

Make the most of Xerces-C++, Part 2

A DOM implementation

Return to article.


Listing 10. Creating a formatter for serialization
                #include "XercesString.h"

void save_to_file(DOMDocument *pDoc, const char *strPath)
{
  XercesString wstrPath( XMLString::transcode(strPath) );
  if (wstrPath)
  {
    DOMWriterImpl writer;
    LocalFileFormatTarget fileTarget(wstrPath);

    // write the resulting document.
    writer.setEncoding( XercesString("UTF-8") );
    writer.writeNode(&fileTarget, *pDoc);
  }
}

void dump_xml(DOMDocument *pDoc)
{
  DOMImplementation *pImplement = NULL;
  // these two are needed to display DOM output.
  DOMWriter *pSerializer = NULL;
  XMLFormatTarget *pTarget = NULL;

  // get a serializer, an instance of DOMWriter (the "LS" stands for load-save).
  pImplement = DOMImplementationRegistry::getDOMImplementation(XercesString("LS"));
  pSerializer = ( (DOMImplementationLS*)pImplement )->createDOMWriter();
  pTarget = new StdOutFormatTarget();
  // set user specified end of line sequence and output encoding
  pSerializer->setNewLine( XercesString("\n") );

  // set feature if the serializer supports the feature/mode
  if ( pSerializer->canSetFeature(XMLUni::fgDOMWRTSplitCdataSections, false) )
  	pSerializer->setFeature(XMLUni::fgDOMWRTSplitCdataSections, false);

  if ( pSerializer->canSetFeature(XMLUni::fgDOMWRTDiscardDefaultContent, false) )
  	pSerializer->setFeature(XMLUni::fgDOMWRTDiscardDefaultContent, false);

  // turn off serializer "pretty print" option
  if ( pSerializer->canSetFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false) )
  	pSerializer->setFeature(XMLUni::fgDOMWRTFormatPrettyPrint, false);

  if ( pSerializer->canSetFeature(XMLUni::fgDOMWRTBOM, false) )
  	pSerializer->setFeature(XMLUni::fgDOMWRTBOM, false);

  pSerializer->writeNode(pTarget, *pDoc);

}

Return to article.