javax.xml.xpath.XPath.compile()方法的使用及代码示例

x33g5p2x  于2022-02-02 转载在 其他  
字(11.5k)|赞(0)|评价(0)|浏览(306)

本文整理了Java中javax.xml.xpath.XPath.compile()方法的一些代码示例,展示了XPath.compile()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。XPath.compile()方法的具体详情如下:
包路径:javax.xml.xpath.XPath
类名称:XPath
方法名:compile

XPath.compile介绍

[英]Compile an XPath expression for later evaluation.

If expression contains any XPathFunctions, they must be available via the XPathFunctionResolver. An XPathExpressionException will be thrown if the XPathFunction cannot be resolved with the XPathFunctionResolver.

If expression is null, a NullPointerException is thrown.
[中]编译一个XPath表达式,以便以后进行计算。
如果expression包含任何XPathFunctions,则它们必须通过XPathFunctionResolver可用。如果XPathFunction无法用XPathFunctionResolver解析,则会抛出XPathExpressionException。
如果expressionnull,则会抛出NullPointerException

代码示例

代码示例来源: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: gocd/gocd

private static String evaluate(XPathFactory factory, InputSource inputSource, String xpath)
    throws XPathExpressionException {
  XPathExpression expression = factory.newXPath().compile(xpath);
  return expression.evaluate(inputSource).trim();
}

代码示例来源:origin: spring-projects/spring-framework

private static XPathExpression compileXpathExpression(String expression,
    @Nullable Map<String, String> namespaces) throws XPathExpressionException {
  SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
  namespaceContext.setBindings(namespaces != null ? namespaces : Collections.emptyMap());
  XPath xpath = XPathFactory.newInstance().newXPath();
  xpath.setNamespaceContext(namespaceContext);
  return xpath.compile(expression);
}

代码示例来源: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: spring-projects/spring-roo

/**
 * Checks in under a given root element whether it can find a child elements
 * which match the XPath expression supplied. Returns a {@link List} of
 * {@link Element} if they exist. Please note that the XPath parser used is
 * NOT namespace aware. So if you want to find a element <beans><sec:http>
 * you need to use the following XPath expression '/beans/http'.
 * 
 * @param xPathExpression the xPathExpression
 * @param root the parent DOM element
 * @return a {@link List} of type {@link Element} if discovered, otherwise
 *         an empty list (never null)
 */
public static List<Element> findElements(final String xPathExpression, final Element root) {
 final List<Element> elements = new ArrayList<Element>();
 NodeList nodes = null;
 try {
  XPathExpression expr = COMPILED_EXPRESSION_CACHE.get(xPathExpression);
  if (expr == null) {
   expr = XPATH.compile(xPathExpression);
   COMPILED_EXPRESSION_CACHE.put(xPathExpression, expr);
  }
  nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET);
 } catch (final XPathExpressionException e) {
  throw new IllegalArgumentException("Unable evaluate xpath expression", e);
 }
 for (int i = 0, n = nodes.getLength(); i < n; i++) {
  elements.add((Element) nodes.item(i));
 }
 return elements;
}

代码示例来源:origin: apache/drill

public Object eval(String xml, String path, QName qname) {
 if (xml == null || path == null || qname == null) {
  return null;
 }
 if (xml.length() == 0 || path.length() == 0) {
  return null;
 }
 if (!path.equals(oldPath)) {
  try {
   expression = xpath.compile(path);
  } catch (XPathExpressionException e) {
   expression = null;
  }
  oldPath = path;
 }
 if (expression == null) {
  return null;
 }
 reader.set(xml);
 try {
  return expression.evaluate(inputSource, qname);
 } catch (XPathExpressionException e) {
  throw new RuntimeException ("Invalid expression '" + oldPath + "'", e);
 }
}

代码示例来源: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: stackoverflow.com

String url = "http://stackoverflow.com/questions/3152138";
Document document = new Tidy().parseDOM(new URL(url).openStream(), null);
XPath xpath = XPathFactory.newInstance().newXPath();

Node question = (Node) xpath.compile("//*[@id='question']//*[contains(@class,'post-text')]//p[1]").evaluate(document, XPathConstants.NODE);
System.out.println("Question: " + question.getFirstChild().getNodeValue());

NodeList answerers = (NodeList) xpath.compile("//*[@id='answers']//*[contains(@class,'user-details')]//a[1]").evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < answerers.getLength(); i++) {
  System.out.println("Answerer: " + answerers.item(i).getFirstChild().getNodeValue());
}

代码示例来源:origin: Tencent/tinker

private static XPathExpression createExpression(String expressionStr) {
  try {
    return XPathFactory.newInstance().newXPath().compile(expressionStr);
  } catch (XPathExpressionException e) {
    throw new AaptUtilException(e);
  }
}

代码示例来源:origin: real-logic/simple-binary-encoding

/**
 * Scan XML for all message definitions and save in map
 *
 * @param document      for the XML parsing
 * @param xPath         for XPath expression reuse
 * @param typeByNameMap to use for Type objects
 * @return {@link java.util.Map} of schemaId to Message
 * @throws Exception on parsing error.
 */
public static Map<Long, Message> findMessages(
  final Document document, final XPath xPath, final Map<String, Type> typeByNameMap) throws Exception
{
  final Map<Long, Message> messageByIdMap = new HashMap<>();
  final ObjectHashSet<String> distinctNames = new ObjectHashSet<>();
  forEach((NodeList)xPath.compile(MESSAGE_XPATH_EXPR).evaluate(document, XPathConstants.NODESET),
    (node) -> addMessageWithIdCheck(distinctNames, messageByIdMap, new Message(node, typeByNameMap), node));
  return messageByIdMap;
}

代码示例来源:origin: stackoverflow.com

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("<Your xml doc uri>");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//Type[@type_id=\"4218\"]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

代码示例来源:origin: gocd/gocd

public static boolean nodeExists(InputSource inputSource, String xpath) throws XPathExpressionException {
  XPathFactory factory = XPathFactory.newInstance();
  XPathExpression expression = factory.newXPath().compile(xpath);
  Boolean b = (Boolean) expression.evaluate(inputSource, XPathConstants.BOOLEAN);
  return b != null && b;
}

代码示例来源:origin: org.hamcrest/hamcrest-all

private static XPathExpression compiledXPath(String xPathExpression, NamespaceContext namespaceContext) {
  try {
    final XPath xPath = XPathFactory.newInstance().newXPath();
    if (namespaceContext != null) {
      xPath.setNamespaceContext(namespaceContext);
    }
    return xPath.compile(xPathExpression);
  } catch (XPathExpressionException e) {
    throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e);
  }
}

代码示例来源:origin: stackoverflow.com

public static void main(String[] args) 
 throws ParserConfigurationException, SAXException, 
    IOException, XPathExpressionException {
 DocumentBuilderFactory domFactory = 
 DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); 
 DocumentBuilder builder = domFactory.newDocumentBuilder();
 Document doc = builder.parse("persons.xml");
 XPath xpath = XPathFactory.newInstance().newXPath();
   // XPath Query for showing all nodes value
 XPathExpression expr = xpath.compile("//person/*/text()");
 Object result = expr.evaluate(doc, XPathConstants.NODESET);
 NodeList nodes = (NodeList) result;
 for (int i = 0; i < nodes.getLength(); i++) {
  System.out.println(nodes.item(i).getNodeValue()); 
 }
}

代码示例来源:origin: stackoverflow.com

XPathFactory xpathFactory = XPathFactory.newInstance();
// XPath to find empty text nodes.
XPathExpression xpathExp = xpathFactory.newXPath().compile(
    "//text()[normalize-space(.) = '']");  
NodeList emptyTextNodes = (NodeList) 
    xpathExp.evaluate(doc, XPathConstants.NODESET);

// Remove each empty text node from document.
for (int i = 0; i < emptyTextNodes.getLength(); i++) {
  Node emptyTextNode = emptyTextNodes.item(i);
  emptyTextNode.getParentNode().removeChild(emptyTextNode);
}

代码示例来源:origin: dreamhead/moco

public XPathRequestExtractor(final String xpath) {
  XPathFactory xPathfactory = XPathFactory.newInstance();
  XPath target = xPathfactory.newXPath();
  try {
    xPathExpression = target.compile(xpath);
  } catch (XPathExpressionException e) {
    throw new IllegalArgumentException(e);
  }
}

代码示例来源: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: sannies/mp4parser

private static long latestTimestamp(Document document) {
  XPathFactory xPathfactory = XPathFactory.newInstance();
  XPath xpath = xPathfactory.newXPath();
  xpath.setNamespaceContext(TtmlHelpers.NAMESPACE_CONTEXT);
  try {
    XPathExpression xp = xpath.compile("//*[name()='p']");
    NodeList timedNodes = (NodeList) xp.evaluate(document, XPathConstants.NODESET);
    long lastTimeStamp = 0;
    for (int i = 0; i < timedNodes.getLength(); i++) {
      lastTimeStamp = Math.max(getEndTime(timedNodes.item(i)), lastTimeStamp);
    }
    return lastTimeStamp;
  } catch (XPathExpressionException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: opentripplanner/OpenTripPlanner

public void setPath(String path) {
  this.path = path;
  XPathFactory factory = XPathFactory.newInstance();
  XPath xpath = factory.newXPath();
  try {
    xpathExpr = xpath.compile(path);
  } catch (XPathExpressionException e) {
    throw new RuntimeException(e);
  }
}

代码示例来源:origin: stackoverflow.com

"\r\n" + //
    "</urn:ResponseStatus>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new java.io.ByteArrayInputStream(xml.getBytes()));
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new NamespaceContext() {
  public String getNamespaceURI(String prefix) {
XPathExpression expr = xpath.compile("//urn:ResponseStatus");
Object result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
  Node currentItem = nodes.item(i);
  System.out.println("found node -> " + currentItem.getLocalName() + " (namespace: " + currentItem.getNamespaceURI() + ")");

相关文章