Format a DOM Document
In this chapter you will learn:
Format XML with Transformer
Transformer
can convert XML data to a format defined
its properties. The following code sets the indent to 4.
import java.io.StringReader;
import java.io.StringWriter;
//from ja va2 s .c o m
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
public class Main {
public static void main(String[] args) throws Exception {
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlRecords));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(is);
format(doc);
}
public static void format(Document doc )throws Exception{
DOMSource domSource = new DOMSource(doc);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
System.out.println(sw.toString());
}
static String xmlRecords =
"<data>" +
" <employee>" +
" <name>Tom</name>"+
" <title>Manager</title>" +
" </employee>" +
" <employee>" +
" <name>Jerry</name>"+
" <title>Programmer</title>" +
" </employee>" +
"</data>";
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » XML