CHAPTER 9 ■ WRITING AND READING XML
File domOutput = new File(fileName);
FileOutputStream domOutputStream
= new FileOutputStream(domOutput, true);
domOutputStream.write(xmlContent.getBytes());
domOutputStream.close();
System.out.println(fileName + “ was successfully written”);
} catch (FileNotFoundException fnfe) {
System.out.println("Couldn't find a file called " + fileName);
System.exit(1);
} catch (IOException ioe) {
System.out.println("Couldn't write to a file called " + fileName);
System.exit(1);
}
}
}
■ Tip Use a StringBuilder object to create a string whenever you need to append strings onto other strings.
If you use the string concatenation operator (+), the JVM creates a new String object but also keeps the previous
String object in memory, which quickly consumes a great deal of memory. Modern JVMs have gotten better about
handling this problem, but it remains an issue, and good practice dictates using StringBuilder when you have more
than one or two concatenations to do.
As you can see, I've carved it up into a few methods to cleanly and clearly separate the parts of the
algorithm. That's a practice you'll see many developers follow, and it’s good to embrace this when code
complexity reaches a certain level. Every programmer has a different threshold for when they think a
long method should become multiple methods. My own threshold is pretty low. A method doesn't have
to get very long before I start itching to split it. In this case, splitting the code also lets me handle the
Exception objects thrown by each step separately.
The process for creating XML with DOM is fairly straightforward:
- Create an empty Document object (the top-level DOM object that contains
everything else). That's done in the createDocument method. - Create the elements and attributes (and their children, grandchildren, and so
on, as needed) and add the elements and attributes to the Document object.
The createElements method performs this step. - Convert the contents of the DOM object to a String object. The
createXMLString method does this step for you. - Write the String object to the target (a file in this case). The writeXMLToFile
method creates your file and puts your XML into the file.