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 {
     
        @XBRead("/*")
        Element getRootElement();
     
        @XBWrite("/*")
        void setRootElement(Element rootElement);
     
    }
    public interface Element {
     
        @XBRead(".")
        Element addAttribute(Attribute attribute);
     
        @XBWrite("@{1}")
        Element addAttribute(String name, @XBValue String value);
     
        @XBRead("@{0}")
        Attribute attribute(String name);
     
        @XBRead("count(@*)")
        int attributeCount();
     
        @XBRead("@*")
        List<Attribute> attributes();
     
        @XBRead("@{0}")
        String attributeValue(String attributeName);
     
        @XBRead("./{0}")
        Element element(String name);
     
        @XBRead("./*")
        List<Element> elements();
     
        @XBRead("name()")
        String getName();
     
        @XBRead(".")
        String getText();
     
    }
    public interface Attribute {
     
        @XBRead("name()")
        String getName();
     
        @XBRead(".")
        String getValue();
    }

Example Code

XBProjector projector = new XBProjector();
 
Document document =projector.io().fromURLAnnotation(Document.class);
Element element = document.getRootElement();
System.out.println(element.getName());
Element element2 = element.element("eelement");
System.out.println(element2.getText());
Attribute attribute = element2.attribute("eattribute");
System.out.println(attribute.getValue());
 
org.w3c.dom.Element newRootNode = ((DOMAccess)document).getDOMOwnerDocument().createElement("newRoot");
Element newRootElement = projector.projectDOMNode(newRootNode, Element.class);
 
document.setRootElement(newRootElement);
System.out.println(document);