xml_write: Writing XML data to disk

Previous: Functions except for xml_read ] [ Top: index ] [ Next: xml_prepend: Inserting elements ]

Writing the contents of one of our XML structures out into a file is simple. We've got two different variants on this function; one writes the entire element (xml_write) and the other writes just the content of the element (xml_writecontent).
 
void xml_write (FILE * file, XML * xml)
{
   ATTR * attr;
   ELEMENTLIST * list;
First, if the element we're working on is plain text, we just write it out.
 
   if (xml->name == NULL) {
      fprintf (file, "%s", xml->attrs->value);
      return;
   }
It's a regular element, so we open the element and write the name.
 
   fprintf (file, "<%s", xml->name);
   attr = xml->attrs;
   while (attr != NULL) {
      fprintf (file, " %s=\"%s\"", attr->name, attr->value);
      attr = attr->next;
   }
If the element has no children (this includes text), then we close the tag as an empty tag, and we're finished.
 
   if (xml->children == NULL) {
      fprintf (file, "/>");
      return;
   } else  fprintf (file, ">");
Otherwise we track down the list of children and write each of them, recursively.
 
   xml_writecontent (file, xml);
And finally, if there were children, then we need to close the tag with the full close.
 
   fprintf (file, "</%s>", xml->name);
}
The weakness of this function currently is that in the absence of plain text there will never be a line break. Not good -- but I don't see a good algorithm for doing it better while ruling out the possibility of inserting line breaks where they'll be errors.

Let's go ahead and define our xml_writecontent.
 
void xml_writecontent (FILE * file, XML * xml)
{
   ELEMENTLIST * list;

   list = xml->children;
   while (list) {
      xml_write (file, list->element);
      list = list->next;
   }
}
Previous: Functions except for xml_read ] [ Top: index ] [ Next: xml_prepend: Inserting elements ]


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.