Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 9 ■ WRITING AND READING XML


// Here's where we add content to the XML document private static void
createElements(Document doc) {
// Create the root element
Element poem = doc.createElement("poem");
poem.setAttribute("title", Poem.getTitle());
poem.setAttribute("author", Poem.getAuthor());

// Add the root element to the document
doc.appendChild(poem);

// Create the child elements
for (String lineIn : Poem.getLines() ) {
Element line = doc.createElement("line");
Text lineText = doc.createTextNode(lineIn);
line.appendChild(lineText);
// Add each element to the root element poem.appendChild(line);
}
}

// Here's where we convert the DOM object
// into a String that contains XML private static String createXMLString(Document doc) {
// Transform the DOM to a String
Transformer transformer = null;
StringWriter stringWriter = new StringWriter();
try {
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
"no");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");

// Create a string to contain the XML from the Document object
stringWriter = new StringWriter();
StreamResult result = new StreamResult(stringWriter);
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
} catch (TransformerConfigurationException e) {
System.out.println("Couldn't create a Transformer");
System.exit(1);
} catch (TransformerException e) {
System.out.println("Couldn't transform DOM to a String");
System.exit(1);
}
return stringWriter.toString();
}

// Here's where we turn the String holding the XML
// into a file private static void writeXMLToFile(String xmlContent) {
String fileName = "C:" + File.separator + "test"
+ File.separator + "domoutput.xml";
try {
Free download pdf