Java XPath Get getStringValue(String targetDoc, String xpathExp, String encoding)

Here you can find the source of getStringValue(String targetDoc, String xpathExp, String encoding)

Description

get String Value

License

Open Source License

Declaration

public static String getStringValue(String targetDoc, String xpathExp, String encoding) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayInputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;

public class Main {
    private static DocumentBuilderFactory factory;

    public static String getStringValue(String targetDoc, String xpathExp, String encoding) throws Exception {
        DocumentBuilder builder = factory.newDocumentBuilder();

        Document doc = builder.parse(new ByteArrayInputStream(targetDoc.getBytes(encoding)));

        XPathFactory pathFactory = XPathFactory.newInstance();

        XPath xpath = pathFactory.newXPath();

        XPathExpression pathExpression = xpath.compile(xpathExp);

        String result = (String) pathExpression.evaluate(doc, XPathConstants.STRING);
        if (result != null) {
            result = result.trim();/*  w  w w .  j  ava  2  s  .c  o m*/
        }
        return result;
    }
}

Related

  1. getString(final String xPath, final Object item)
  2. getString(Node node, XPathExpression expr)
  3. getStringByXPath(String xml, String xpathStr)
  4. getStringValue(Node node, XPathExpression expression)
  5. getStringValue(Object doc, XPathExpression path)
  6. getStringValueByXPath(Node node, String xPath)
  7. getText(String xPathExpression, Node node)
  8. getTextNodes(Node contextNode, String xPath)
  9. getValidXpath(String xPath, NamespaceContext context)