xml_copy: making fresh copies of XML

Previous: inserting things: xml_insertbefore and xml_insertafter ] [ Top: index ] [ Next: xml_read: Using expat to parse XML files into memory ]

Since an XML element knows its parent, you run into problems when you want an element to be moved from one tree into another: if you free the first, the second is broken. To avoid this kind of unpleasantness, use xml_copy.
 
XML * xml_copy (XML * orig)
{
   XML * copy = NULL;
   char * text;
   XML * child;
   ATTR * attr;

   if (!orig) return copy;

   if (!orig->name) {
      text = xml_string (orig);
      copy = xml_createtext (text);
      free (text);
      return copy;
   }

   copy = xml_create (orig->name);
   attr = orig->attrs;
   while (attr) {
      xml_set (copy, attr->name, attr->value);
      attr = attr->next;
   }

   child = xml_first (orig);
   while (child) {
      xml_append (copy, xml_copy (child));
      child = xml_next (child);
   }

   return (copy);
}
Similarly, there arise plenty of situations (at least in wftk) where you want to copy over attributes and content from one XML into another, but want to leave existing attributes alone.
 
XML * xml_copyinto (XML * target, XML * source)
{
   char * text;
   XML * child;
   ATTR * attr;

   if (!source) return target;
   if (!source->name) {
      text = xml_string (source);
      if (target) {
         xml_append (target, xml_createtext (text));
         free (text);
         return (target);
      }
      target = xml_createtext (text);
      return (target);
   }

   if (!target) target = xml_create (source->name);

   attr = source->attrs;
   while (attr) {
      xml_set (target, attr->name, attr->value);
      attr = attr->next;
   }

   child = xml_first (source);
   while (child) {
      xml_append (target, xml_copy (child));
      child = xml_next (child);
   }

   return (target);
}
Previous: inserting things: xml_insertbefore and xml_insertafter ] [ Top: index ] [ Next: xml_read: Using expat to parse XML files into memory ]


This code and documentation are released under the terms of the GNU license. They are additionally copyright (c) 2000, Vivtek. All rights reserved except those explicitly granted under the terms of the GNU license. This presentation was created using LPML.