Fork me on GitHub

Tutorial 8

E08: Demonstrating API Mimicry

In this tutorial we make extensive use of XPath to mimicry an existing 3rd Party-API.

Projection API

In this example we do something special:

  • Projection of a complete unknown XML structure.
  • Building our Java API analog to DOM4J.

    The result is a generic Java API you can use to analyze every XML document.

    public interface Document {
        Element getRootElement();
        void setRootElement(Element rootElement);
    public interface Element {
        Element addAttribute(Attribute attribute);
        Element addAttribute(String name, @XBValue String value);
        Attribute attribute(String name);
        int attributeCount();
        List<Attribute> attributes();
        String attributeValue(String attributeName);
        Element element(String name);
        List<Element> elements();
        String getName();
        String getText();
    public interface Attribute {
        String getName();
        String getValue();

Example Code

XBProjector projector = new XBProjector();
Document document;
Element element = document.getRootElement();
Element element2 = element.element("eelement");
Attribute attribute = element2.attribute("eattribute");
org.w3c.dom.Element newRootNode = ((DOMAccess)document).getDOMOwnerDocument().createElement("newRoot");
Element newRootElement = projector.projectDOMNode(newRootNode, Element.class);