2-minute tutorial to learn how to use avc-binding-dom.
Getting Started
Say you have a given XML file, book.xml:
<book title="Treasure Island"> <reference url="http://en.wikipedia.org/wiki/Treasure_Island" lang="en"/> <reference url="http://fr.wikipedia.org/wiki/L'Île_au_trésor" lang="fr"/> <publishedIn>1883</publishedIn> <author> <name>Robert Louis Stevenson</name> <name>R. L. Stevenson</name> </author> </book>
Say now you want to use this data into some code, instantiating Java objects for the need.
The avc-binding-dom API allows you to declare interfaces annotated with XPath expressions corresponding to the XML nodes you're interested in:
package aaa.bbb.ccc; import net.avcompris.binding.annotation.XPath; @XPath("/book") public interface Book { @XPath("@title") String getTitle(); @XPath("publishedIn") int getPublishYear(); @XPath("author/name") String[] getAuthorNames(); @XPath("reference") MyBookReference[] getReferences(); interface MyBookReference { @XPath("@url") String getUrl(); @XPath("@lang") String getLang(); } }
Our example uses an inner interface for convenience, but avc-binding-dom also knows how to bind sub-nodes to independent interfaces.
More information about the @XPath annotation may be found in the avc-binding-common project's API Documentation. See also the XPath Expressions and Return Types pages.
With our example, binding will occur the following way:
... import java.io.File; import net.avcompris.binding.dom.helper.DomBinderUtils; ... final Book book = DomBinderUtils.xmlContentToJava(new File("book.xml", Book.class);
Or, in an equivalent way:
... import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import net.avcompris.binding.dom.DomBinder; import net.avcompris.binding.dom.impl.DefaultDomBinder; import org.w3c.dom.Document; ... final Document document = DocumentBuilderFactory.newInstance() .newDocumentBuilder().parse(new File("book.xml")); final DomBinder binder = new DefaultDomBinder(); final Book book = binder.bind(document, Book.class);
(This sample code is in the project's test sources: GettingStartedExamplesTest.)
More information about DomBinder and DefaultDomBinder classes may be found in the API Documentation.
Of course you get all of the expectable assertions:
... import static org.junit.Assert.assertEquals; ... assertEquals("Treasure Island", book.getTitle()); assertEquals(1883, book.getPublishYear()); assertEquals(2, book.getAuthorNames().length); assertEquals("Robert Louis Stevenson", book.getAuthorNames()[0]); assertEquals("R. L. Stevenson", book.getAuthorNames()[1]); assertEquals(2, book.getReferences().length); assertEquals("en", book.getReferences()[0].getLang()); assertEquals("fr", book.getReferences()[1].getLang()); ...
Not in this 2-minute tutorial:
- See how avc-binding-dom handles XML Namespaces.
- More on XPath Expressions.
- Naming Conventions to be used for your method names.