Tabnine Logo
XPath
Code IndexAdd Tabnine to your IDE (free)

How to use
XPath
in
javax.xml.xpath

Best Java code snippets using javax.xml.xpath.XPath (Showing top 20 results out of 7,623)

Refine searchRefine arrow

  • XPathFactory
  • DocumentBuilder
  • DocumentBuilderFactory
  • XPathExpression
  • NodeList
  • Node
origin: stackoverflow.com

 Document doc = DocumentBuilderFactory.newInstance()
 .newDocumentBuilder().parse(new InputSource(new StringReader(html)));

XPathExpression xpath = XPathFactory.newInstance()
 .newXPath().compile("//td[text()=\"Description\"]/following-sibling::td[2]");

String result = (String) xpath.evaluate(doc, XPathConstants.STRING);
origin: stackoverflow.com

 //obtain Document somehow, doesn't matter how
DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
org.w3c.dom.Document doc = b.parse(new FileInputStream("page.html"));

//Evaluate XPath against Document itself
XPath xPath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xPath.evaluate("/html/body/p/div[3]/a",
    doc.getDocumentElement(), XPathConstants.NODESET);
for (int i = 0; i < nodes.getLength(); ++i) {
  Element e = (Element) nodes.item(i);
}
origin: sannies/mp4parser

protected long firstTimestamp(Document document) {
  XPathFactory xPathfactory = XPathFactory.newInstance();
  XPath xpath = xPathfactory.newXPath();
  xpath.setNamespaceContext(TtmlHelpers.NAMESPACE_CONTEXT);
  try {
    XPathExpression xp = xpath.compile("//*[@begin]");
    NodeList timedNodes = (NodeList) xp.evaluate(document, XPathConstants.NODESET);
    long firstTimestamp = Long.MAX_VALUE;
    for (int i = 0; i < timedNodes.getLength(); i++) {
      firstTimestamp = Math.min(getStartTime(timedNodes.item(i)), firstTimestamp);
    }
    return firstTimestamp;
  } catch (XPathExpressionException e) {
    throw new RuntimeException(e);
  }
}
origin: apache/geode

public static NodeList query(Node node, String searchString, XPathContext xpathcontext)
  throws XPathExpressionException {
 XPath xpath = XPathFactory.newInstance().newXPath();
 xpath.setNamespaceContext(xpathcontext);
 return (NodeList) xpath.evaluate(searchString, node, XPathConstants.NODESET);
}
origin: kiegroup/jbpm

public Object evaluate(final ProcessContext context) throws Exception {        
  XPathFactory factory = XPathFactory.newInstance();
  XPath xpathEvaluator = factory.newXPath();
  xpathEvaluator.setXPathFunctionResolver( 
      new  XPathFunctionResolver() {
        public XPathFunction resolveFunction(QName functionName, int arity)
  xpathEvaluator.setXPathVariableResolver(new XPathVariableResolver() {
  xpathEvaluator.setNamespaceContext(new NamespaceContext() {
    private static final String DROOLS_NAMESPACE_URI = "http://www.jboss.org/drools";
    private String[] prefixes = {"drools", "bpmn2"};
  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  return xpathEvaluator.evaluate(this.expression, builder.newDocument(), XPathConstants.BOOLEAN);
origin: sannies/mp4parser

raf.getChannel().write(xmlSamplePart);
raf.close();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(f);
XPathFactory xPathfactory = XPathFactory.newInstance();
NamespaceContext ctx = new NamespaceContext() {
  public String getNamespaceURI(String prefix) {
XPath xpath = xPathfactory.newXPath();
xpath.setNamespaceContext(ctx);
XPathExpression expr = xpath.compile("/ttml:tt/ttml:body/ttml:div/@smpte:backgroundImage");
NodeList nl = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
HashSet<String> names = new HashSet<String>();
for (int n = 0; n < nl.getLength(); n++) {
  names.add(nl.item(n).getNodeValue());
System.out.println(document.getFirstChild().getTextContent());
origin: kiegroup/jbpm

String to = assignment.getTo();
XPathFactory factory = XPathFactory.newInstance();
XPath xpathFrom = factory.newXPath();
XPathExpression exprFrom = xpathFrom.compile(from);
XPath xpathTo = factory.newXPath();
XPathExpression exprTo = xpathTo.compile(to);
    parent = ((org.w3c.dom.Node) target).getParentNode();
  targetElem = exprTo.evaluate(parent, XPathConstants.NODE);
   nl = (NodeList) exprFrom.evaluate(source, XPathConstants.NODESET);
} else if (source instanceof String) {
  DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
  Document doc = builder.newDocument();
if (nl.getLength() == 0) {
  throw new RuntimeException("Nothing was selected by the from expression " + from + " on " + sourceExpr);
for (int i = 0 ; i < nl.getLength(); i++) {
origin: jeremylong/DependencyCheck

try {
  final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder();
  final Document d = db.parse(stream);
  final XPath xpath = XPathFactory.newInstance().newXPath();
  final List<NugetPackageReference> packages = new ArrayList<>();
  final NodeList nodeList = (NodeList) xpath.evaluate("//PackageReference", d, XPathConstants.NODESET);
  for (int i = 0; i < nodeList.getLength(); i++) {
    final Node node = nodeList.item(i);
    final NamedNodeMap attrs = node.getAttributes();
      final NugetPackageReference npr = new NugetPackageReference();
      npr.setId(include.getNodeValue());
      npr.setVersion(version.getNodeValue());
origin: stackoverflow.com

DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
domFactory.setNamespaceAware(true);
try {
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document dDoc = builder.parse("E:/test.xml");
  XPath xPath = XPathFactory.newInstance().newXPath();
  xPath.setNamespaceContext(new MyNamespaceContext());
  NodeList nl = (NodeList) xPath.evaluate("/ns:root/ns:author", dDoc, XPathConstants.NODESET);
  System.out.println(nl.getLength());
} catch (Exception e) {
  e.printStackTrace();
origin: jenkinsci/jenkins

/**
 * The a "value" from an XML file using XPath.
 * @param xpath The XPath expression to select the value.
 * @param document The document from which the value is to be extracted.
 * @return The data value. An empty {@link String} is returned when the expression does not evaluate
 * to anything in the document.
 * @throws XPathExpressionException Invalid XPath expression.
 * @since 2.0
 */
public static String getValue(String xpath, Document document) throws XPathExpressionException {
  XPath xPathProcessor = XPathFactory.newInstance().newXPath();
  return xPathProcessor.compile(xpath).evaluate(document);
}
origin: real-logic/simple-binary-encoding

final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  factory.setXIncludeAware(true);
  factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false);
final Document document = factory.newDocumentBuilder().parse(in);
final XPath xPath = XPathFactory.newInstance().newXPath();
errorHandler.checkIfShouldExit();
final Node schemaNode = (Node)xPath.compile(MESSAGE_SCHEMA_XPATH_EXPR).evaluate(document, XPathConstants.NODE);
final MessageSchema messageSchema = new MessageSchema(schemaNode, typeByNameMap, messageByIdMap);
errorHandler.checkIfShouldExit();
origin: quartz-scheduler/quartz

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setNamespaceAware(true);
docBuilderFactory.setValidating(true);
docBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
docBuilder = docBuilderFactory.newDocumentBuilder();
docBuilder.setErrorHandler(this);
xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(nsContext);
origin: wildfly/wildfly

public XMLSanitizer(String pattern, VirtualFileFilter filter) throws Exception {
  this.filter = filter;
  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  expression = xpath.compile(pattern);
  DocumentBuilderFactory DBfactory = DocumentBuilderFactory.newInstance();
  DBfactory.setNamespaceAware(true);
  builder = DBfactory.newDocumentBuilder();
  builder.setErrorHandler(null);
  TransformerFactory transformerFactory = TransformerFactory.newInstance();
  transformer = transformerFactory.newTransformer();
}
origin: traccar/traccar

public SpotProtocolDecoder(Protocol protocol) {
  super(protocol);
  try {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    builderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
    builderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    builderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    builderFactory.setXIncludeAware(false);
    builderFactory.setExpandEntityReferences(false);
    documentBuilder = builderFactory.newDocumentBuilder();
    xPath = XPathFactory.newInstance().newXPath();
    messageExpression = xPath.compile("//messageList/message");
  } catch (ParserConfigurationException | XPathExpressionException e) {
    throw new RuntimeException(e);
  }
}
origin: BroadleafCommerce/BroadleafCommerce

while(resourceList.hasNext()) {
  ResourceInputStream myStream = resourceList.nextResource();
  Document doc = builder.parse(myStream);
  NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET);
  int length = nodeList.getLength();
  for (int j=0;j<length;j++) {
    Element element = (Element) nodeList.item(j);
    Resource resource = loader.getResource(element.getAttribute("resource"));
    ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(), resource.getURL().toString());
    resourceList.addEmbeddedResource(ris);
    element.getParentNode().removeChild(element);
origin: plutext/docx4j

synchronized(xPath) {
  getNamespaceContext().registerPrefixMappings(prefixMappings);
  n = (Node)xPath.evaluate(xpath, doc, XPathConstants.NODE );
if (n.getChildNodes() !=null
    && n.getChildNodes().getLength() > 0) {
  NodeList nodes = n.getChildNodes();
  for (int i = nodes.getLength(); i>0; i--) {
    n.removeChild( nodes.item(i-1));
origin: BroadleafCommerce/BroadleafCommerce

/**
 * Common routine to remove all children nodes from the passed element container
 * @param parentElement
 * @param nodeName
 * @throws XPathExpressionException
 */
protected void clearNode(Element parentElement, String nodeName) throws XPathExpressionException {
  if (parentElement.hasChildNodes()) {
    NodeList children = (NodeList) xPath.evaluate(nodeName, parentElement, XPathConstants.NODESET);
    for (int j = 0; j < children.getLength(); j++) {
      parentElement.removeChild(children.item(j));
    }
    children = parentElement.getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
      if (children.item(j).getNodeName().equalsIgnoreCase("#text")) {
        parentElement.removeChild(children.item(j));
      }
    }
  }
}

origin: plutext/docx4j

List<Node> result = new ArrayList<Node>();
xpath.setNamespaceContext(nsContext);
NodeList nl = (NodeList) xpath.evaluate(xpathExpression, node, XPathConstants.NODESET);
  log.debug("evaluate returned " + nl.getLength() );
if (nl.getLength()==0) {
  log.info("no results for xpath " + xpathExpression );
for( int i=0; i<nl.getLength(); i++ ) {
  result.add(nl.item(i));
origin: apache/hive

  expression = xpath.compile(path);
 } catch (XPathExpressionException e) {
  expression = null;
 try {
  initializeDocumentBuilderFactory();
  builder = dbf.newDocumentBuilder();
 } catch (ParserConfigurationException e) {
  throw new RuntimeException("Error instantiating DocumentBuilder, cannot build xml parser", e);
 return expression.evaluate(builder.parse(inputSource), qname);
} catch (XPathExpressionException e) {
 throw new RuntimeException ("Invalid expression '" + oldPath + "'", e);
origin: apache/activemq

private boolean evaluate(String text) {
  try {
    InputSource inputSource = new InputSource(new StringReader(text));
    Document inputDocument = builder.parse(inputSource);
    return ((Boolean) xpath.evaluate(xpathExpression, inputDocument, XPathConstants.BOOLEAN)).booleanValue();
  } catch (Exception e) {
    return false;
  }
}
javax.xml.xpathXPath

Javadoc

XPath provides access to the XPath evaluation environment and expressions.

Evaluation of XPath Expressions.
context If a request is made to evaluate the expression in the absence of a context item, an empty document node will be used for the context. For the purposes of evaluating XPath expressions, a DocumentFragment is treated like a Document node.
variables If the expression contains a variable reference, its value will be found through the XPathVariableResolverset with #setXPathVariableResolver(XPathVariableResolver resolver). An XPathExpressionException is raised if the variable resolver is undefined or the resolver returns null for the variable. The value of a variable must be immutable through the course of any single evaluation.

functions If the expression contains a function reference, the function will be found through the XPathFunctionResolverset with #setXPathFunctionResolver(XPathFunctionResolver resolver). An XPathExpressionException is raised if the function resolver is undefined or the function resolver returns null for the function.

QNames QNames in the expression are resolved against the XPath namespace context set with #setNamespaceContext(NamespaceContext nsContext).
result This result of evaluating an expression is converted to an instance of the desired return type. Valid return types are defined in XPathConstants. Conversion to the return type follows XPath conversion rules.

Most used methods

  • compile
    Compile an XPath expression for later evaluation. If expression contains any XPathFunctions, they m
  • evaluate
    Evaluate an XPath expression in the context of the specified InputSource and return the result as th
  • setNamespaceContext
    Establish a namespace context. A NullPointerException is thrown if nsContext is null.
  • setXPathVariableResolver
    Establish a variable resolver. A NullPointerException is thrown if resolver is null.
  • setXPathFunctionResolver
    Establish a function resolver. A NullPointerException is thrown if resolver is null.
  • getNamespaceContext
    Return the current namespace context. null is returned in no namespace context is in effect.
  • reset
    Reset this XPath to its original configuration. XPath is reset to the same state as when it was cre
  • getXPathFunctionResolver
    Return the current function resolver. null is returned in no function resolver is in effect.
  • getXPathVariableResolver
    Return the current variable resolver. null is returned in no variable resolver is in effect.
  • <init>

Popular in Java

  • Start an intent from android
  • scheduleAtFixedRate (ScheduledExecutorService)
  • scheduleAtFixedRate (Timer)
  • getResourceAsStream (ClassLoader)
  • Color (java.awt)
    The Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary
  • Collections (java.util)
    This class consists exclusively of static methods that operate on or return collections. It contains
  • SortedMap (java.util)
    A map that has its keys ordered. The sorting is according to either the natural ordering of its keys
  • ImageIO (javax.imageio)
  • Logger (org.apache.log4j)
    This is the central class in the log4j package. Most logging operations, except configuration, are d
  • SAXParseException (org.xml.sax)
    Encapsulate an XML parse error or warning.> This module, both source code and documentation, is in t
  • Best IntelliJ plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now