Java XPath Expression string(String fileName, String xpathExpression)

Here you can find the source of string(String fileName, String xpathExpression)

Description

string

License

Apache License

Declaration

public static String string(String fileName, String xpathExpression) 

Method Source Code

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

public class Main {

    public static String string(String fileName, String xpathExpression) {
        TransformerFactory transFact = TransformerFactory.newInstance();
        try {/* w ww  .  j  a  v  a 2  s  .co m*/
            Transformer transFormer = transFact.newTransformer();
            DOMResult dom = new DOMResult();
            transFormer.transform(new StreamSource(new FileInputStream(
                    new File(fileName))), dom);
            XPath xpath = XPathFactory.newInstance().newXPath();
            XPathExpression expression = xpath.compile(xpathExpression);
            String value = (String) expression.evaluate(dom.getNode(),
                    XPathConstants.STRING);
            return value;
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. readXmlNodeChildFromFile(String xPath, String path, NamespaceContext nsContext)
  2. replaceXPathNode(Node replaceThis, Node replaceWith)
  3. singleXPathNode(String expression, Node node)
  4. streamNodes(String xpath, Object node)
  5. string(Node context, String expression)
  6. valueOf(Node node, String xpath, NamespaceContext context)
  7. xmlValueOf(Node node, String xpathExpression)
  8. xPathStr(String expr, Object context)
  9. xpathToNode(String xpathQuery, Object domObject)