javax.xml.xpath.XPath类的使用及代码示例

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

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

XPath介绍

[英]XPath provides access to the XPath evaluation environment and expressions.
Evaluation of XPath Expressions.contextIf 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. variablesIf 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.

functionsIf 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.

QNamesQNames in the expression are resolved against the XPath namespace context set with #setNamespaceContext(NamespaceContext nsContext). resultThis 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.
[中]XPath提供对XPath计算环境和表达式的访问。
XPath表达式的计算。context如果请求在没有上下文项的情况下计算表达式,则上下文将使用空文档节点。为了计算XPath表达式,DocumentFragment被视为文档节点。变量如果表达式包含变量引用,则其值将通过带有#setXPathVariableResolver(XPathVariableResolver resolver)的XPathVariableResolver集合找到。如果变量解析程序未定义或解析程序为变量返回null,则会引发XPathExpressionException。变量的值必须在任何单个评估过程中保持不变。
函数如果表达式包含函数引用,将通过带有#setXPathFunctionResolver(XPathFunctionResolver resolver)的XPathFunctionResolver集合找到函数。如果函数解析程序未定义或函数解析程序为函数返回null,则会引发XPathExpressionException。
表达式中的QNamesQNames根据#setNamespaceContext(NamespaceContext nsContext)的XPath命名空间上下文集进行解析。结果计算表达式的结果将转换为所需返回类型的实例。有效的返回类型在XPathConstants中定义。到返回类型的转换遵循XPath转换规则。

代码示例

代码示例来源: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;
  }
}

相关文章