Writing XML Contents Using SAX


When compared to DOM, writing an XML document using SAX isn't straightforward because of its sequential processing nature. To accomplish this, you need to manually insert the right XML element at the right location. To insert an element, you use the following:

  • q Use the startElement() method to insert the element's start tag

  • q Use the characters() method to insert the text content of the element

  • q Use the endElement() to insert the element's end tag

Listing 13-3 shows the code required to add a new element named <Discount> as a child element to each of the <Product> elements.

Listing 13-3: Writing XML contents using SAX

image from book
      import java.io.*;      import javax.xml.parsers.SAXParserFactory;      import javax.xml.parsers.SAXParser;      import org.xml.sax.*;      import org.xml.sax.helpers.*;      public class ProductsWriting extends DefaultHandler      {        static int numberOfLines = 0;        static String indentation = "";        static String text[] = new String[1000];        public static void main(String[] args) throws Exception        {          System.out.println("Start of Products...");          ProductsWriting readerObj = new ProductsWriting();          readerObj.read(args[0]);          try         {          FileWriter writer = new FileWriter("Products_New.xml");          for (int index = 0; index < numberOfLines; index++)          {            writer.write(text[index].toCharArray());            writer.write('\n');         }         writer.close();         }         catch (Exception e)         {           e.printStackTrace(System.err);         }      }      public void read(String fileName) throws Exception      {        XMLReader reader = XMLReaderFactory.createXMLReader          ("org.apache.xerces.parsers.SAXParser");        reader.setContentHandler(this);        reader.setErrorHandler(this);        reader.parse(fileName);      }      public void startDocument()      {        text[numberOfLines] = indentation;        text[numberOfLines] += "<?xml version=\"1.0\" encoding=\""+           "UTF-8" + "\"?>";        numberOfLines++;      }      public void processingInstruction(String target, String data)      {        text[numberOfLines] = indentation;        text[numberOfLines] += "<?";        text[numberOfLines] += target;        if (data != null && data.length() > 0)        {          text[numberOfLines] += ' ';          text[numberOfLines] += data;        }        text[numberOfLines] += "?>";        numberOfLines++;      }      public void startElement(String uri, String localName,          String qualifiedName, Attributes attributes)      {          text[numberOfLines] = indentation;          indentation += "    ";          text[numberOfLines] += '<';          text[numberOfLines] += qualifiedName;          if (attributes != null)          {           int numberAttributes = attributes.getLength();          for (int loopIndex = 0; loopIndex < numberAttributes; loopIndex++)          {            text[numberOfLines] += ' ';            text[numberOfLines] += attributes.getQName(loopIndex);            text[numberOfLines] += "=\"";            text[numberOfLines] += attributes.getValue(loopIndex);            text[numberOfLines] += '"';          }          }          text[numberOfLines] += '>';          numberOfLines++;      }      public void characters(char characters[], int start, int length)      {        String characterData = (new String(characters, start, length)).trim();          if(characterData.indexOf("\n") < 0 && characterData.length() > 0)          {          text[numberOfLines] = indentation;          text[numberOfLines] += characterData;          numberOfLines++;          }      }      public void endElement(String uri, String localName, String qualifiedName)      {        indentation = indentation.substring(0, indentation.length() - 4);        text[numberOfLines] = indentation;        text[numberOfLines] += "</";        text[numberOfLines] += qualifiedName;        text[numberOfLines] += '>';        numberOfLines++;        if (qualifiedName.equals("ProductNumber"))        {          startElement("", "Discount", "Discount", null);          characters("10%".toCharArray(), 0, "10%".length());          endElement("", "Discount", "Discount");         }      }      public void warning(SAXParseException exception)      {        System.err.println("Warning: " + exception.getMessage());      }      public void error(SAXParseException exception)      {        System.err.println("Error: " + exception.getMessage());      }      public void fatalError(SAXParseException exception)         {          System.err.println("Fatal error: " + exception.getMessage());        }      } 
image from book

In the preceding lines of code, the endElement() method is where the majority of the work occurs including identifying the location where the <Discount> element needs to be inserted. Since you want to insert the <Discount> element right next to <ProductNumber>, you check for the presence of ProductNumber as the name of the element. After you figure out the exact location, you insert the new element through the combination of startElement(), characters(), and endElement(), methods.

Figure 13-4 shows the contents of the Products_New.xml file when viewed in the browser.

image from book
Figure 13-4




Professional XML
Professional XML (Programmer to Programmer)
ISBN: 0471777773
EAN: 2147483647
Year: 2004
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net