|
ExampleUsage
How to use the XMLBuilder.
Example UsageRead below for examples that show how you would use the XMLBuilder utility to create and manipulate XML documents like the following: <?xml version="1.0" encoding="UTF-8"?>
<Projects>
<java-xmlbuilder language="Java" scm="SVN">
<Location type="URL">http://code.google.com/p/java-xmlbuilder/</Location>
</java-xmlbuilder>
<JetS3t language="Java" scm="CVS">
<Location type="URL">http://jets3t.s3.amazonaws.com/index.html</Location>
</JetS3t>
</Projects>Create a New XML DocumentTo begin, you create a new builder and XML document by specifying the name of the document's root element. See ExampleUsage#Parse_XML if you want to start with an existing XML document. XMLBuilder builder = XMLBuilder.create("Projects");The XMLBuilder object returned by the create method, and by all other XML manipulation methods, provides methods that you can use to add more nodes to the document. For example, to add the java-xmlbuilder and JetS3t nodes to the root element you could do the following. XMLBuilder e1 = builder.element("java-xmlbuilder");
XMLBuilder e2 = builder.element("JetS3t");And to add attributes or further sub-elements to the two new elements, you could call the appropriate methods on the variables assigned to each new node like so: e1.attribute("language", "Java");
e1.attribute("scm", "SVN");This is straight-forward enough, but it is far more verbose than necessary because the code does not take advantage of XMLBuilder's method-chaining feature. Method ChainingEvery XMLBuilder method that adds something to the XML document will return an XMLBuilder object that represents either a newly-added element, or the element to which something has been added. This feature means that you can chain together many method calls without the need to assign intermediate objects to variables. With this in mind, here is code that performs the same job as the code above without any unnecessary variables. XMLBuilder builder = XMLBuilder.create("Projects")
.element("java-xmlbuilder")
.attribute("language", "Java")
.attribute("scm", "SVN")
.element("Location")
.up()
.up()
.element("JetS3t");There are two important things to notice in the code above:
Shorthand MethodsTo make your XML building code even shorter and easier to type, there are shorthand synonyms for every XML manipulation method. Instead of calling element() you can use the elem() or e() methods, and instead of typing attribute() you can use attr() or a(). Here is the complete code to build our example XML document using shorthand methods. XMLBuilder builder = XMLBuilder.create("Projects")
.e("java-xmlbuilder")
.a("language", "Java")
.a("scm","SVN")
.e("Location")
.a("type", "URL")
.t("http://code.google.com/p/java-xmlbuilder/")
.up()
.up()
.e("JetS3t")
.a("language", "Java")
.a("scm","CVS")
.e("Location")
.a("type", "URL")
.t("http://jets3t.s3.amazonaws.com/index.html");The following methods are available for adding items to the XML document:
OutputXMLBuilder includes two convenient methods for outputting a document. You can use the toWriter method to print the document to an output stream or file: PrintWriter writer = new PrintWriter(new FileOutputStream("projects.xml"));
builder.toWriter(writer, outputProperties);Or you can convert the document straight to a text string: builder.asString(outputProperties); Both of these output methods take an outputProperties parameter that you can use to control how the output options. Any output properties you provide are forwarded to the underlying Transformer object that is used to serialize the XML document. You might specify any non-standard properties like so: Properties outputProperties = new Properties();
// Explicitly identify the output as an XML document
outputProperties.put(javax.xml.transform.OutputKeys.METHOD, "xml");
// Pretty-print the XML output (doesn't work in all cases)
outputProperties.put(javax.xml.transform.OutputKeys.INDENT, "yes");
// Get 2-space indenting when using the Apache transformer
outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "2");If you do not wish to change the default properties for your output, you can provide a null value for outputProperties. Accessing the Underlying DocumentBecause XMLBuilder merely acts as a layer on top of the standard JAXP XML document building tools, you can easily access the underlying Element or Document objects if you need to manipulate them in ways that XMLBuilder does not allow. To obtain the Element represented by any given XMLBuilder node: org.w3c.dom.Element element = xmlBuilderNode.getElement(); To obtain the entire XML document: org.w3c.dom.Document doc = builder.getDocument(); You can also use the root() method to quickly obtain the builder object that represents the document's root element, no matter deep an element hierarchy your code has built: org.w3c.dom.Element rootElement =
XMLBuilder.create("This")
.e("Element")
.e("Hierarchy")
.e("Is")
.e("Really")
.e("Very")
.e("Deep")
.e("Indeed")
.root().getElement();Parse XMLIf you already have an XML document to which you need to add nodes or attributes, you can create a new XMLBuilder instance by parsing an InputSource: XMLBuilder builder = XMLBuilder.parse( new InputSource(new StringReader(YOUR_XML_DOCUMENT))); Parsing an existing document will produce an XMLBuilder object pointing at the document's root Element node. If you add elements or attributes to this builder object, they will be added to the document's root element. If you need to add nodes elsewhere in the parsed document, you will need to find the correct location in the document using XPath statements. Find Nodes with XPathTo add nodes at a specific point in an XML document, you can use XPath to obtain an XMLBuilder at the correct location. The XMLBuilder#xpathFind method takes an XPath query string and returns a builder object located at the first Element that matches the query. XMLBuilder firstLocationBuilder = builder.xpathFind("//Location");Note that the XPath query provided to this method must resolve to at least one Element node. If the query does not match any nodes, or if the first match is anything other than an Element, the method will throw an XPathExpressionException. Like all other XMLBuilder methods, this method can be easily chained to others when adding nodes. Here is an example that adds a second element, Location2, inside the JetS3t element of our example document. builder.xpathFind("//JetS3t").elem("Location2").attr("type", "Testing");To produce: <Projects>
<java-xmlbuilder language="Java" scm="SVN">
<Location type="URL">http://code.google.com/p/java-xmlbuilder/</Location>
</java-xmlbuilder>
<JetS3t language="Java" scm="CVS">
<Location type="URL">http://jets3t.s3.amazonaws.com/index.html</Location>
<Location2 type="Testing"/>
</JetS3t>
</Projects>
|
Sign in to add a comment
Nice & Simple thank you for your great effort
Emad Al-Bloushi
VEry nice and useful (feels like jquery).
But do you have some performance comparisons with existing xml parsers/builders? (dom4j,...).
Keep up the great work!
I like the idea very much. But wouldn't it be better if it doesn't create a new builder on every call. How about return simply this on every call and at the same time mark the current element/position inside the Builder. For instance,
...
public XmlRequestBuilder? root() {
}public XMLBuilder element(String name) {
}