Java XPath Expression extractValue(String xml, String xpathExpression)

Here you can find the source of extractValue(String xml, String xpathExpression)

Description

extract Value

License

Artistic License

Declaration

public static String extractValue(String xml, String xpathExpression) 

Method Source Code


//package com.java2s;
//License from project: Artistic License 

import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

public class Main {
    public static String extractValue(String xml, String xpathExpression) {
        String actual;//from  www. j  a  va 2  s .  co m
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setNamespaceAware(true);
            documentBuilderFactory.setIgnoringElementContentWhitespace(true);
            DocumentBuilder docBuilder = documentBuilderFactory.newDocumentBuilder();

            byte[] bytes = xml.getBytes("UTF-8");
            InputStream inputStream = new ByteArrayInputStream(bytes);
            Document doc = docBuilder.parse(inputStream);
            XPathFactory xPathFactory = XPathFactory.newInstance();
            XPath xpath = xPathFactory.newXPath();

            actual = xpath.evaluate(xpathExpression, doc, XPathConstants.STRING).toString();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return actual;
    }
}

Related

  1. executePath(final Node node, final XPathExpression expression)
  2. expr(String xpathStr)
  3. extractNode(XPath xpath, String nodePath, String xmlString)
  4. extractNodeList(XPath xpath, String nodePath, String xmlString)
  5. extractNodes(File xmlFile, String xpathLocator)
  6. findElements(final String xPathExpression, final Element root)
  7. hasAnimatedPng(ImageReader reader)
  8. isLegalXPath(final String xPath)
  9. isValidFilter(String xPathString)