13 avr 2012

Requêtes XPath, un jeu d’enfant avec Jaxp13XPathTemplate de Spring

Catégorie : Non classéJohnny Beuve @ 8 h 33 min

Un exemple autonome de test unitaire pour comprendre comment fonctionne le Template Jaxp13XPathTemplate du framework Spring . Cela sert à ça aussi les tests ;-)


public class XpathSimpleTest {

    private String xmlBody = "<root\n" +
            "xmlns:h=\"http://www.w3.org/TR/html4/\"\n" +
            "xmlns:f=\"http://www.w3schools.com/furniture\">\n" +
            "\n" +
            "<h:table>\n" +
            "  <h:tr>\n" +
            "    <h:td>Apples</h:td>\n" +
            "    <h:td>Bananas</h:td>\n" +
            "  </h:tr>\n" +
            "</h:table>\n" +
            "\n" +
            "<f:table>\n" +
            "  <f:name>African Coffee Table</f:name>\n" +
            "  <f:width>80</f:width>\n" +
            "  <f:length>120</f:length>\n" +
            "</f:table>\n" +
            "\n" +
            "</root>";

    @org.junit.Test
    public void exampleXPathTemplate()
            throws javax.xml.parsers.ParserConfigurationException,
            org.xml.sax.SAXException,
            java.io.IOException {

        org.w3c.dom.Document doc = null;

        // string xml en Document
        javax.xml.parsers.DocumentBuilder db;
        javax.xml.parsers.DocumentBuilderFactory
                factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        db = factory.newDocumentBuilder();
        java.io.InputStream
                is = new java.io.ByteArrayInputStream(xmlBody.getBytes());
        doc = db.parse(is);

        // get namespace as Hasmap<localName, URI>
        java.util.HashMap<String, String> namespaces = new java.util.HashMap<String, String>();
        for (int i = 0; i < doc.getDocumentElement().getAttributes().getLength(); i++) {
            String localName = doc.getDocumentElement().getAttributes().item(i).getLocalName();
            String textContent = doc.getDocumentElement().getAttributes().item(i).getTextContent();
            namespaces.put(localName, textContent);
        }

        // Requete Xpath
        javax.xml.transform.dom.DOMSource domSource = new javax.xml.transform.dom.DOMSource(doc);
        org.springframework.xml.xpath.XPathOperations
                template = new org.springframework.xml.xpath.Jaxp13XPathTemplate();
        ((org.springframework.xml.xpath.Jaxp13XPathTemplate) template).setNamespaces(namespaces);
        junit.framework.Assert.assertEquals(" La valeur root/f:table/f:length ",
                "120",
                template.evaluateAsString("root/f:table/f:length", domSource));
        junit.framework.Assert.assertEquals(" Un path  root/f:table/f:pathNexistePas ramène ",
                "",
                template.evaluateAsString("root/f:table/f:pathNexistePas", domSource));
    }
}

Mots-clefs :

Laisser une réponse