Example usage for javax.xml.xpath XPathFactory newInstance

List of usage examples for javax.xml.xpath XPathFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.xpath XPathFactory newInstance.

Prototype

public static XPathFactory newInstance() 

Source Link

Document

Get a new XPathFactory instance using the default object model, #DEFAULT_OBJECT_MODEL_URI , the W3C DOM.

This method is functionally equivalent to:

 newInstance(DEFAULT_OBJECT_MODEL_URI) 

Since the implementation for the W3C DOM is always available, this method will never fail.

Usage

From source file:pakiet.rt.DelicjaXMLParser.java

private void parse() throws SAXException, IOException, XPathExpressionException, ParserConfigurationException {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(new ByteArrayInputStream(xmlInputString.getBytes()));
    XPath xPath = XPathFactory.newInstance().newXPath();
    String userName = xPath.evaluate("//*[1]/@user", xmlDocument);
    resp.setUser(userName);/*  w  ww  . ja  va2  s . c om*/
    System.out.println("test: " + userName);

    try {
        builder = builderFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }

}

From source file:au.edu.rmit.GalagoSearchClient.java

protected Node xpathGetNode(Document doc, String expr)
        throws XPathExpressionException, UnsupportedEncodingException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    return (Node) xpath.compile(expr).evaluate(doc, XPathConstants.NODE);
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.opinion.OpinionCorpusFactory.java

@Override
protected OpinionCorpusFactory addXmlPacket(OpinionCorpus corpus, InputStream input)
        throws ParserConfigurationException, SAXException, IOException, XPathException {

    Validate.notNull(corpus, CannedMessages.NULL_ARGUMENT, "corpus");
    Validate.notNull(input, CannedMessages.NULL_ARGUMENT, "input");

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*  w ww .  j  a v a 2  s. co m*/
    Document doc = domFactory.newDocumentBuilder().parse(input);

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    OpinionDocumentFactory opinionFactory;

    if ("document".equals(doc.getDocumentElement().getLocalName())) {
        opinionFactory = new OpinionDocumentFactory().setCorpus(corpus).setXmlNode(doc.getDocumentElement());
        corpus.addDocument(opinionFactory.create());
        return this;
    }

    Node corpusNode = (Node) xpath.compile("/corpus").evaluate(doc, XPathConstants.NODE);
    if (corpusNode == null) {
        corpusNode = Validate.notNull(doc.getDocumentElement(), CannedMessages.NULL_ARGUMENT, "/corpus");
    }

    String title = (String) xpath.compile("./@title").evaluate(corpusNode, XPathConstants.STRING);
    String description = (String) xpath.compile("./@description").evaluate(corpusNode, XPathConstants.STRING);
    String language = (String) xpath.compile("./@language").evaluate(corpusNode, XPathConstants.STRING);

    if (StringUtils.isNotEmpty(title)) {
        corpus.setTitle(title);
    }

    if (StringUtils.isNotEmpty(description)) {
        corpus.setDescription(description);
    }

    if (StringUtils.isNotEmpty(language)) {
        corpus.setLanguage(language);
    }

    NodeList documentNodes = (NodeList) xpath.compile("./document").evaluate(corpusNode,
            XPathConstants.NODESET);
    if (documentNodes == null || documentNodes.getLength() == 0) {
        documentNodes = corpusNode.getChildNodes();
        Validate.isTrue(documentNodes != null && documentNodes.getLength() > 0, CannedMessages.NULL_ARGUMENT,
                "/corpus/document");
    }

    for (int index = 0; index < documentNodes.getLength(); index++) {
        opinionFactory = new OpinionDocumentFactory().setCorpus(corpus).setXmlNode(documentNodes.item(index));
        corpus.addDocument(opinionFactory.create());
    }

    return this;
}

From source file:com.orange.ngsi.model.ContextAttributeModelTest.java

@Test
public void serializationXMLContextAttribute() throws IOException, XPathExpressionException {

    ContextAttribute contextAttribute = new ContextAttribute("A", "T", "22");

    ObjectMapper xmlmapper = new XmlMapper();
    String xml = xmlmapper.writeValueAsString(contextAttribute);

    assertTrue(xml.contains("A"));
    assertTrue(xml.contains("T"));
    assertTrue(xml.contains("22"));

    String xpathExpr = "/ContextAttribute/name";
    XPath xPath = XPathFactory.newInstance().newXPath();
    assertEquals("A", xPath.evaluate(xpathExpr, new InputSource(new StringReader(xml))));
}

From source file:br.gov.lexml.parser.documentoarticulado.LexMLUtil.java

public static String formatLexML(String xml) {
    String retorno = null;/*w w  w .j  a v  a 2s . c  o m*/
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);

        transformer.transform(new DOMSource(document), streamResult);

        retorno = stringWriter.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return retorno;

}

From source file:Main.java

public static final String indenting(Node rootNode) throws XPathExpressionException, TransformerException {

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", rootNode,
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }//  w  w w  .  j  a  va 2  s. c  o  m

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    StringWriter stringWriter = new StringWriter();
    StreamResult streamResult = new StreamResult(stringWriter);

    transformer.transform(new DOMSource(rootNode), streamResult);

    return stringWriter.toString();
}

From source file:com.cognifide.aet.job.common.datafilters.removenodes.RemoveNodesDataModifier.java

@Override
public void setParameters(Map<String, String> params) throws ParametersException {
    if (params.containsKey(PARAM_XPATH)) {
        xpathString = params.get(PARAM_XPATH);
        XPathFactory xPathfactory = XPathFactory.newInstance();
        XPath xpath = xPathfactory.newXPath();
        try {/* w  w w .j  av  a  2 s.c  o  m*/
            expr = xpath.compile(xpathString);
        } catch (XPathExpressionException e) {
            throw new ParametersException(e.getMessage(), e);
        }
    } else {
        throw new ParametersException("XPath must be provided");
    }

}

From source file:com.autentia.tnt.xml.UtilitiesXPath.java

public static List<List> ExtractReport(String folderReport) {
    List reportList = null;/*from w w  w.j a  v a2s. c om*/
    List filesList = null;
    try {
        reportList = new ArrayList<List>();
        filesList = UtilitiesXML.filesFromFolder(folderReport);

        for (int i = 0; i < filesList.size(); i++) {
            List<List> tmp = new ArrayList<List>();
            Document doc = UtilitiesXML.file2Document(filesList.get(i).toString());
            XPath xpath = XPathFactory.newInstance().newXPath();

            if (log.isDebugEnabled()) {
                log.debug("\n>> Nombre del informe: ");
            }

            expression = "/jasperReport[@name]";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            nameReport = UtilitiesXML.printAttribute("name", nodes);
            nameReport.add(UtilitiesXML.cleanReport(filesList.get(i).toString()));

            if (log.isDebugEnabled()) {
                log.debug(nameReport.toString());
                log.debug("Parametros: ");
            }

            expression = "/jasperReport/parameter[@name]";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersName = UtilitiesXML.printAttribute("name", nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersName.toString());
                log.debug("Clases: ");
            }

            expression = "/jasperReport/paremeter[@class]";
            nameClass = UtilitiesXML.printAttribute("class", nodes);

            if (log.isDebugEnabled()) {
                log.debug(nameClass.toString());
                log.debug("Descripcion de Parametros: ");
            }

            expression = "/jasperReport/parameter/parameterDescription";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersDescription = UtilitiesXML.nodes2String(nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersDescription.toString());
                log.debug("Valores por defectos: ");
            }

            expression = "/jasperReport/parameter/defaultValueExpression";
            nodes = (NodeList) xpath.evaluate(expression, doc.getDocumentElement(), XPathConstants.NODESET);
            parametersDefaultValue = UtilitiesXML.nodes2String(nodes);

            if (log.isDebugEnabled()) {
                log.debug(parametersDefaultValue.toString());
                log.debug("\n------------------------------------");
            }

            tmp.add(nameReport);
            tmp.add(parametersName);
            tmp.add(nameClass);
            tmp.add(parametersDescription);
            tmp.add(parametersDefaultValue);
            reportList.add(tmp);

        }
        log.debug("Lista de informes:" + reportList);

    } catch (Exception e) {
        log.error(e);
    }
    return reportList;

}

From source file:com.intel.hadoop.graphbuilder.demoapps.wikipedia.linkgraph.LinkGraphTokenizer.java

public LinkGraphTokenizer() throws ParserConfigurationException {
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from w  w  w  .j  av a2 s . c o  m*/
    builder = factory.newDocumentBuilder();
    XPathFactory xfactory = XPathFactory.newInstance();
    xpath = xfactory.newXPath();

    vlist = new ArrayList<Vertex<StringType, EmptyType>>();
    elist = new ArrayList<Edge<StringType, EmptyType>>();
    links = new ArrayList<String>();
}

From source file:Main.java

private static NodeList getNodeList(String xmlContent, String expression)
        throws XPathExpressionException, SAXException, IOException, ParserConfigurationException {

    Document document = parse(xmlContent, CHARSET_UTF8);
    XPath xpath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xpath.evaluate(expression, document.getDocumentElement(),
            XPathConstants.NODESET);

    return nodeList;
}