[xsd-users] Deleting empty elements

Boris Kolpackov boris at codesynthesis.com
Tue Jan 27 09:18:01 EST 2009


Hi,

delta42 <delta42 at gmail.com> writes:

>     Due to the complexity of the hierarchy, when creating a new XML document
> I often find it cleaner to code by adding elements before I know whether
> these elements will have any sub-elements. So naturally in some cases when I
> serialize I end up with many empty elements.
> 
>     Is there an easy way to have these removed prior to serializing to a
> stringstream? Or do I have to first serialize them to a stringstream and
> then pass them to Xerces directly and somehow traverse all the elements to
> deal with this?

You can serialize the object model to the DOM document first. This
way you can traverse the document and remove all empty elements.
After that you can serialize the DOM document to stringstream
(there is sample code in the FAQ[1] on how to do this).

The function which cleans up empty elements could look like this
(haven't tested):

void
remove_empty_elements (DOMElement* e)
{
  for (DOMNode* n = e->getFirstChild (); n != 0; )
  {
    if (n->getNodeType () == DOMNode::ELEMENT_NODE)
    {
      DOMElement* ne = static_cast<DOMElement*> (n);
      n = n->getNextSibling ();

      if (ne->getFirstChild () == 0)
      {
        if (ne->getAttributes ().getLength () == 0)        
        {
	  e->removeChild (ne);
          ne->release ();
        }
      }
      else
        remove_empty_elements (ne);
    }
    else
      n = n->getNextSibling ();
  }
}

DOMDocument* doc = ... // Serialize object model to DOM
remove_empty_elements (doc->getDocumentElement ());


[1] http://wiki.codesynthesis.com/Tree/FAQ

Boris




More information about the xsd-users mailing list