java创建XML及开源DOM4J的使用
java
1 import java.io.File; 2 import java.io.StringWriter; 3 4 import javax.xml.parsers.DocumentBuilder; 5 import javax.xml.parsers.DocumentBuilderFactory; 6 import javax.xml.parsers.ParserConfigurationException; 7 import javax.xml.transform.Transformer; 8 import javax.xml.transform.TransformerConfigurationException; 9 import javax.xml.transform.TransformerException; 10 import javax.xml.transform.TransformerFactory; 11 import javax.xml.transform.dom.DOMSource; 12 import javax.xml.transform.stream.StreamResult; 13 14 import org.w3c.dom.Document; 15 import org.w3c.dom.Element; 16 17 18 public class CreatXML { 19 20 public static void main(String[] args) { 21 try { 22 23 24 //DOM 25 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 26 DocumentBuilder builder = factory.newDocumentBuilder(); 27 Document document = builder.newDocument(); 28 Element root = document.createElement("Languages"); 29 root.setAttribute("cat", "it"); 30 31 Element lan1 = document.createElement("lan"); 32 lan1.setAttribute("id", "1"); 33 Element name1 = document.createElement("name"); 34 name1.setTextContent("Java"); 35 Element ide1 = document.createElement("ide"); 36 ide1.setTextContent("Eclipse"); 37 lan1.appendChild(name1); 38 lan1.appendChild(ide1); 39 40 Element lan2 = document.createElement("lan"); 41 lan2.setAttribute("id", "2"); 42 Element name2 = document.createElement("name"); 43 name2.setTextContent("Swift"); 44 Element ide2 = document.createElement("ide"); 45 ide2.setTextContent("XCode"); 46 lan2.appendChild(name2); 47 lan2.appendChild(ide2); 48 49 Element lan3 = document.createElement("lan"); 50 lan3.setAttribute("id", "3"); 51 Element name3 = document.createElement("name"); 52 name3.setTextContent("C#"); 53 Element ide3 = document.createElement("ide"); 54 ide3.setTextContent("Visual Studio"); 55 lan3.appendChild(name3); 56 lan3.appendChild(ide3); 57 58 root.appendChild(lan1); 59 root.appendChild(lan2); 60 root.appendChild(lan3); 61 document.appendChild(root); 62 63 //------------- 64 65 TransformerFactory transformerFactory = TransformerFactory.newInstance(); 66 Transformer transformer = transformerFactory.newTransformer(); 67 transformer.setOutputProperty("encoding", "UTF-8"); 68 69 StringWriter writer = new StringWriter(); 70 transformer.transform(new DOMSource(document), new StreamResult(writer)); 71 System.out.println(writer.toString()); 72 73 transformer.transform(new DOMSource(document), new StreamResult(new File("newxml.xml"))); 74 75 } catch (ParserConfigurationException e) { 76 e.printStackTrace(); 77 } catch (TransformerConfigurationException e) { 78 e.printStackTrace(); 79 } catch (TransformerException e) { 80 e.printStackTrace(); 81 } 82 } 83 84 }
下载地址
DOM4j的使用
1 import org.dom4j.Document; 2 import org.dom4j.DocumentException; 3 import org.dom4j.DocumentHelper; 4 5 6 public class Test { 7 8 public static void main(String[] args) { 9 String xmlString = "<root><people>ACELY</people></root>"; 10 11 try { 12 13 14 15 Document document = DocumentHelper.parseText(xmlString); 16 17 System.out.println(document.asXML()); 18 19 20 21 } catch (DocumentException e) { 22 e.printStackTrace(); 23 } 24 } 25 26 }
DOM4j使用文档
Parsing XML
One of the first things you'll probably want to do is to parse an XML document of some kind. This is easy to do in dom4j. The following code demonstrates how to this.
import java.net.URL; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; public class Foo { public Document parse(URL url) throws DocumentException { SAXReader reader = new SAXReader(); Document document = reader.read(url); return document; } }
Using Iterators
A document can be navigated using a variety of methods that return standard Java Iterators. For example
public void bar(Document document) throws DocumentException { Element root = document.getRootElement(); // iterate through child elements of root for ( Iterator i = root.elementIterator(); i.hasNext(); ) { Element element = (Element) i.next(); // do something } // iterate through child elements of root with element name "foo" for ( Iterator i = root.elementIterator( "foo" ); i.hasNext(); ) { Element foo = (Element) i.next(); // do something } // iterate through attributes of root for ( Iterator i = root.attributeIterator(); i.hasNext(); ) { Attribute attribute = (Attribute) i.next(); // do something } }
Powerful Navigation with XPath
In dom4j XPath expressions can be evaluated on the Document or on any Node in the tree (such as Attribute, Element or ProcessingInstruction). This allows complex navigation throughout the document with a single line of code. For example.
public void bar(Document document) { List list = document.selectNodes( "//foo/bar" ); Node node = document.selectSingleNode( "//foo/bar/author" ); String name = node.valueOf( "@name" ); }
For example if you wish to find all the hypertext links in an XHTML document the following code would do the trick.
public void findLinks(Document document) throws DocumentException { List list = document.selectNodes( "//a/@href" ); for (Iterator iter = list.iterator(); iter.hasNext(); ) { Attribute attribute = (Attribute) iter.next(); String url = attribute.getValue(); } }
If you need any help learning the XPath language we highly recommend the Zvon tutorial which allows you to learn by example.
Fast Looping
If you ever have to walk a large XML document tree then for performance we recommend you use the fast looping method which avoids the cost of creating an Iterator object for each loop. For example
public void treeWalk(Document document) { treeWalk( document.getRootElement() ); } public void treeWalk(Element element) { for ( int i = 0, size = element.nodeCount(); i < size; i++ ) { Node node = element.node(i); if ( node instanceof Element ) { treeWalk( (Element) node ); } else { // do something.... } } }
Creating a new XML document
Often in dom4j you will need to create a new document from scratch. Here's an example of doing that.
import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; public class Foo { public Document createDocument() { Document document = DocumentHelper.createDocument(); Element root = document.addElement( "root" ); Element author1 = root.addElement( "author" ) .addAttribute( "name", "James" ) .addAttribute( "location", "UK" ) .addText( "James Strachan" ); Element author2 = root.addElement( "author" ) .addAttribute( "name", "Bob" ) .addAttribute( "location", "US" ) .addText( "Bob McWhirter" ); return document; } }
Writing a document to a file
A quick and easy way to write a Document (or any Node) to a Writer is via the write() method.
FileWriter out = new FileWriter( "foo.xml" ); document.write( out );
If you want to be able to change the format of the output, such as pretty printing or a compact format, or you want to be able to work with Writer objects or OutputStream objects as the destination, then you can use the XMLWriter class.
import org.dom4j.Document; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class Foo { public void write(Document document) throws IOException { // lets write to a file XMLWriter writer = new XMLWriter( new FileWriter( "output.xml" ) ); writer.write( document ); writer.close(); // Pretty print the document to System.out OutputFormat format = OutputFormat.createPrettyPrint(); writer = new XMLWriter( System.out, format ); writer.write( document ); // Compact format to System.out format = OutputFormat.createCompactFormat(); writer = new XMLWriter( System.out, format ); writer.write( document ); } }
Converting to and from Strings
If you have a reference to a Document or any other Node such as an Attribute or Element, you can turn it into the default XML text via the asXML() method.
Document document = ...; String text = document.asXML();
If you have some XML as a String you can parse it back into a Document again using the helper method DocumentHelper.parseText()
String text = "<person> <name>James</name> </person>"; Document document = DocumentHelper.parseText(text);
Styling a Document with XSLT
Applying XSLT on a Document is quite straightforward using the JAXP API from Sun. This allows you to work against any XSLT engine such as Xalan or SAXON. Here is an example of using JAXP to create a transformer and then applying it to a Document.
import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import org.dom4j.Document; import org.dom4j.io.DocumentResult; import org.dom4j.io.DocumentSource; public class Foo { public Document styleDocument( Document document, String stylesheet ) throws Exception { // load the transformer using JAXP TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer( new StreamSource( stylesheet ) ); // now lets style the given document DocumentSource source = new DocumentSource( document ); DocumentResult result = new DocumentResult(); transformer.transform( source, result ); // return the transformed document Document transformedDoc = result.getDocument(); return transformedDoc; } }