// Fig. 16.18: XMLCreator.java
// Creates XML
package cartXML;
import java.io.*;
import org.w3c.dom.*;
import java.util.*;
import javax.xml.parsers.*;

public class XMLCreator
{
   private Document document;

   public Node initialize( String rootElement )
   {
      try {
         System.setProperty(
            "javax.xml.parsers.DocumentBuilderFactory",
            "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" );
         System.setProperty(
           "javax.xml.parsers.SAXParserFactory",
           "org.apache.xerces.jaxp.SAXParserFactoryImpl" );
         DocumentBuilderFactory dbf =
            DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();

         document = db.newDocument();

         Node rootNode = document.createElement( rootElement );

         document.appendChild( rootNode );
         return rootNode;
      }
      catch ( DOMException domex ) {
         domex.printStackTrace();
      }
      catch ( ParserConfigurationException pcex ) {
         pcex.printStackTrace();
      }

      return null;
   }

   public Node addChild( Node parentNode, String element )
   {
      parentNode.appendChild( document.createElement(
         element ) );
      return parentNode.getLastChild();
   }

   public void addTextNode( Node parentNode, String element )
   {
      parentNode.appendChild( document.createTextNode(
         element ) );
   }

   public void addAttribute( Node parentNode, String name,
      String value )
   {
      Element element = ( Element ) parentNode;

      element.setAttribute( name, value );
   }

   public Document getDocument()
   {
      return document;
   }
}

/*
 **************************************************************************
 * (C) Copyright 2001 by Deitel & Associates, Inc. and Prentice Hall.     *
 * All Rights Reserved.                                                   *
 *                                                                        *
 * DISCLAIMER: The authors and publisher of this book have used their     *
 * best efforts in preparing the book. These efforts include the          *
 * development, research, and testing of the theories and programs        *
 * to determine their effectiveness. The authors and publisher make       *
 * no warranty of any kind, expressed or implied, with regard to these    *
 * programs or to the documentation contained in these books. The authors *
 * and publisher shall not be liable in any event for incidental or       *
 * consequential damages in connection with, or arising out of, the       *
 * furnishing, performance, or use of these programs.                     *
 **************************************************************************
*/
