Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 9 ■ WRITING AND READING XML

System.exit(1);
} catch (IOException ioe) {
System.out.println("Couldn't write to a file called " + fileName);
System.exit(1);
}
}
}


As you can see, the code is substantially simpler and easier to follow. It also performs more quickly.
Again, it doesn't have some of the output features from DOM (no XML header, for example), but it works
if you just need a simple XML document.


Reading XML


To read XML, you can use either DOM or SAX. As mentioned earlier in this chapter, DOM is handy when
you can be sure that your XML content will fit into the memory you have available. However, DOM fails
when the input is too large. SAX, on the other hand, can handle any amount of input. For SAX, you need
only as much memory as the largest element needs (usually not much, unless you're doing something
such as processing large images or items where a single element can contain a large amount of data).


Reading XML with DOM


Here's the source for a program that reads XML with DOM. For this program to work, you need to
create a file named poemsource.xml and put it in your C:\test (on Windows) or C:/test (on Unix or
Linux) directory. You can use the contents of the domoutput.xml file as the contents of the
poemsource.xml file.


Listing 9-6. Reading XML with DOM


package com.bryantcs.examples.xml;


import java.io.File;
import java.io.IOException;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

Free download pdf