XML DOM Parsing
// build DOM
URL url = new URL("<path-to-file>");
SAXReader reader = new SAXReader();
Document document = reader.read(url);
Use XPath expression to navigate the document tree.
Processing a single node
Node node = document.selectSingleNode("/html/head/meta[@name=keywords]");
String content = node.valueOf("@content");
To process multiple results, we need to use a List
Document document; // assume is instantiated
// all src attributes of any img element
List list = document.selectNodes("//**/img/@src");
// loop the list
for( Iterator it = list.iterator(); it.hasNext(); ){
Attribute att = (Attribute) it.next();
String uri = att.getValue();
}
Document Creation
You can create a docuemnt from scratch by using the DocumentHelper#createDocuemnt()
. Adding nodes and attributes is easy and intuitive.
Document document = DocumentHelper.createDocument();
element root = document.addElement("root");
// add a child
Element elChild1 = root.addElement("child")
.addAttribute("name","Nicholas")
.addAttribute("age","15")
.addText("Nic is the first child);
// add a second child
Element elChild2 = root.addElement("child")
.addAttribute("name","Valentine")
.addAttribute("age","12")
.addText("Vale is the second child);
Writing document to File
To write a document you can use the Document.write()
method
FileWriter fw = new FileWriter("my-out-file.xml");
document.write( fw );
You can change writing formats and parameters. Below there is a code example.
// prepare an output format
OutputFormat format = OutputFormat.createPrettyPrint();
XmlWriter xw = new XMLWriter( System.out, format );
xw.write( document );
Converting to and from String
You can convert a document, or a node into corresponding xml String.
// here get xml of entire document
String text = document.asXML();
If you have XML in a String, you can get build the represented document
String xmlText ="<root><child>Nich</child><child>Vale</child></root>";
Document doc = DocumentHelper.parseText(xmlText);
Apply XSL-Transform
To apply XSL-Transform to a document you can use the JAXP Api from sun, by using any XSLT engine you want, like Xalan or Saxon.
Document document; //.. assume instantiated
String xslturi; //..
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer( new StreamSource(xslturi) );
// executes the transform
DocumentSource source = new DocumentSource( document );
DocumentResult result = new DocumentResult();
t.transform( source, result );
// get output document
Document output = result.getDocument();
References
- dom4j quickstart guide, dom4j on GitHub
0 Comments