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

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

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

XPath.evaluate介绍

[英]Evaluate an XPath expression in the specified context and return the result as a String.

This method calls #evaluate(String expression,Object item,QName returnType) with a returnType of XPathConstants#STRING.

See Evaluation of XPath Expressions for context item evaluation, variable, function and QName resolution and return type conversion.

If a null value is provided for item, an empty document will be used for the context. If expression is null, then a NullPointerException is thrown.
[中]在指定的上下文中计算XPath表达式,并将结果作为String返回。
此方法使用returnType个XPathConstants#字符串调用#evaluate(字符串表达式、对象项、QName返回类型)。
有关上下文项求值、变量、函数和QName解析以及返回类型转换,请参见{$0$}。
如果为item提供了null值,则上下文将使用空文档。如果expressionnull,则会抛出NullPointerException

代码示例

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

public static NodeList query(Node node, String searchString) throws XPathExpressionException {
 XPath xpath = XPathFactory.newInstance().newXPath();
 return (NodeList) xpath.evaluate(searchString, node, XPathConstants.NODESET);
}

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

import java.io.FileReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class GuestList {
 public static void main(String[] args) throws Exception {
  XPathFactory factory = XPathFactory.newInstance();
  XPath xPath = factory.newXPath();
  NodeList shows = (NodeList) xPath.evaluate("/schedule/show", new InputSource(new FileReader(
    "tds.xml")), XPathConstants.NODESET);
  for (int i = 0; i < shows.getLength(); i++) {
   Element show = (Element) shows.item(i);
   String guestName = xPath.evaluate("guest/name", show);
   String guestCredit = xPath.evaluate("guest/credit", show);
   System.out.println(show.getAttribute("weekday") + ", " + show.getAttribute("date") + " - "
     + guestName + " (" + guestCredit + ")");
  }
 }
}

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

boolean exists = statusFile.exists();
if (exists) {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    builder = dbf.newDocumentBuilder();
  Document document = builder.parse(statusFile);
  NodeList indexNodeList = (NodeList) xPath.evaluate("/status/index", document, XPathConstants.NODESET);
  Element indexElement = (Element) indexNodeList.item(0);
  status.setLastIndexDate(format.parse(indexElement.getAttribute("dateProcessed")));
  NodeList infos = (NodeList) xPath.evaluate("info", indexElement, XPathConstants.NODESET);
  for (int j = 0; j < infos.getLength(); j++) {
    Element info = (Element) infos.item(j);
    status.getAdditionalInfo().put(info.getAttribute("key"), info.getAttribute("val"));
  NodeList errorsNodeList = (NodeList) xPath.evaluate("/status/errors", document, XPathConstants.NODESET);
  if (errorsNodeList.getLength() > 0) {
    Element errorsElement = (Element) errorsNodeList.item(0);
    NodeList errors = (NodeList) xPath.evaluate("error", errorsElement, XPathConstants.NODESET);
    for (int j = 0; j < errors.getLength(); j++) {
      Element anError = (Element) errors.item(j);
      Long eventId = Long.valueOf(anError.getAttribute("key"));

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

@Override
protected Object decode(
    Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
  FullHttpRequest request = (FullHttpRequest) msg;
  Document document = documentBuilder.parse(new ByteBufferBackedInputStream(request.content().nioBuffer()));
  NodeList nodes = (NodeList) messageExpression.evaluate(document, XPathConstants.NODESET);
  List<Position> positions = new LinkedList<>();
  for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i);
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, xPath.evaluate("esnName", node));
    if (deviceSession != null) {
      Position position = new Position(getProtocolName());
      position.setDeviceId(deviceSession.getDeviceId());
      position.setValid(true);
      position.setTime(DateUtil.parseDate(xPath.evaluate("timestamp", node)));
      position.setLatitude(Double.parseDouble(xPath.evaluate("latitude", node)));
      position.setLongitude(Double.parseDouble(xPath.evaluate("longitude", node)));
      position.set(Position.KEY_EVENT, xPath.evaluate("messageType", node));
      positions.add(position);
    }
  }
  sendResponse(channel, HttpResponseStatus.OK);
  return positions;
}

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

private String xpath(String input, String expression) throws Exception {
  Node node = builderFactory.newDocumentBuilder().parse(new InputSource(new StringReader(input)));
  return (String) xpath.evaluate(expression, node, XPathConstants.STRING);
 }
}

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

String xml = "<resp><status>good</status><msg>hi</msg></resp>";

InputSource source = new InputSource(new StringReader(xml));

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(source);

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();

String msg = xpath.evaluate("/resp/msg", document);
String status = xpath.evaluate("/resp/status", document);

System.out.println("msg=" + msg + ";" + "status=" + status);

代码示例来源:origin: jeremylong/DependencyCheck

try {
  final DocumentBuilder builder = XmlUtils.buildSecureDocumentBuilder();
  final Document doc = builder.parse(conn.getInputStream());
  final XPath xpath = XPathFactory.newInstance().newXPath();
  final String numFound = xpath.evaluate("/response/result/@numFound", doc);
  if ("0".equals(numFound)) {
    missing = true;
  } else {
    result = new ArrayList<>();
    final NodeList docs = (NodeList) xpath.evaluate("/response/result/doc", doc, XPathConstants.NODESET);
    for (int i = 0; i < docs.getLength(); i++) {
      final String g = xpath.evaluate("./str[@name='g']", docs.item(i));
      LOGGER.trace("GroupId: {}", g);
      final String a = xpath.evaluate("./str[@name='a']", docs.item(i));
      LOGGER.trace("ArtifactId: {}", a);
      final String v = xpath.evaluate("./str[@name='v']", docs.item(i));
      final NodeList attributes = (NodeList) xpath.evaluate("./arr[@name='ec']/str", docs.item(i), XPathConstants.NODESET);
      boolean pomAvailable = false;
      boolean jarAvailable = false;
      for (int x = 0; x < attributes.getLength(); x++) {
        final String tmp = xpath.evaluate(".", attributes.item(x));
        if (".pom".equals(tmp)) {
          pomAvailable = true;

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

代码示例来源:origin: plutext/docx4j

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/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: stackoverflow.com

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

  public static void main(String[] args) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder builder = domFactory.newDocumentBuilder();
      Document dDoc = builder.parse("E:/test.xml");

      XPath xPath = XPathFactory.newInstance().newXPath();
      NodeList nl = (NodeList) xPath.evaluate("/root/author", dDoc, XPathConstants.NODESET);
      System.out.println(nl.getLength());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

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

代码示例来源:origin: quartz-scheduler/quartz

NodeList deleteJobGroupNodes = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:pre-processing-commands/q:delete-jobs-in-group",
    document, XPathConstants.NODESET);
NodeList deleteTriggerGroupNodes = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:pre-processing-commands/q:delete-triggers-in-group",
    document, XPathConstants.NODESET);
NodeList deleteJobNodes = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:pre-processing-commands/q:delete-job",
    document, XPathConstants.NODESET);
NodeList deleteTriggerNodes = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:pre-processing-commands/q:delete-trigger",
    document, XPathConstants.NODESET);
NodeList jobNodes = (NodeList) xpath.evaluate("/q:job-scheduling-data/q:schedule/q:job",
    document, XPathConstants.NODESET);
  NodeList jobDataEntries = (NodeList) xpath.evaluate(
      "q:job-data-map/q:entry", jobDetailNode,
      XPathConstants.NODESET);
NodeList triggerEntries = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:schedule/q:trigger/*", document, XPathConstants.NODESET);
  NodeList jobDataEntries = (NodeList) xpath.evaluate(
      "q:job-data-map/q:entry", triggerNode,
      XPathConstants.NODESET);

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

Element errorsElement = null;
clearNode(rootElement, "errors");
NodeList indexNodeList = (NodeList) xPath.evaluate("/status/errors", document, XPathConstants.NODESET);
if (indexNodeList.getLength() > 0) {
  errorsElement = (Element) indexNodeList.item(0);
} else {
  if (status.getIndexErrors().size() > 0) {
  NodeList errors = (NodeList) xPath.evaluate("error[@key='" + entry.getKey() + "']", errorsElement, XPathConstants.NODESET);
  if (errors.getLength() == 0) { //add the error
    Element anError = document.createElement("error");
    anError.setAttribute("key", entry.getKey().toString());

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

import java.io.StringReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;

public class Demo {

  public static void main(String[] args) throws Exception {
    String xml = "<car><manufacturer>toyota</manufacturer></car>";
    String xpath = "/car/manufacturer";
    XPath xPath = XPathFactory.newInstance().newXPath();
    assertEquals("toyota",xPath.evaluate(xpath, new InputSource(new StringReader(xml))));
  }

}

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

  public static void main(String[] args) {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder builder = domFactory.newDocumentBuilder();
      Document dDoc = builder.parse("E:/test.xml");

      XPath xPath = XPathFactory.newInstance().newXPath();
      Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE);
      System.out.println(node.getNodeValue());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}

代码示例来源: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("/packages/package", d, XPathConstants.NODESET);
  for (int i = 0; i < nodeList.getLength(); i++) {
    final Node node = nodeList.item(i);
    final NamedNodeMap attrs = node.getAttributes();
    final Node id = attrs.getNamedItem("id");

代码示例来源:origin: quartz-scheduler/quartz

NodeList deleteJobGroupNodes = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:pre-processing-commands/q:delete-jobs-in-group",
    document, XPathConstants.NODESET);
NodeList deleteTriggerGroupNodes = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:pre-processing-commands/q:delete-triggers-in-group",
    document, XPathConstants.NODESET);
NodeList deleteJobNodes = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:pre-processing-commands/q:delete-job",
    document, XPathConstants.NODESET);
NodeList deleteTriggerNodes = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:pre-processing-commands/q:delete-trigger",
    document, XPathConstants.NODESET);
NodeList jobNodes = (NodeList) xpath.evaluate("/q:job-scheduling-data/q:schedule/q:job",
    document, XPathConstants.NODESET);
  NodeList jobDataEntries = (NodeList) xpath.evaluate(
      "q:job-data-map/q:entry", jobDetailNode,
      XPathConstants.NODESET);
NodeList triggerEntries = (NodeList) xpath.evaluate(
    "/q:job-scheduling-data/q:schedule/q:trigger/*", document, XPathConstants.NODESET);
  NodeList jobDataEntries = (NodeList) xpath.evaluate(
      "q:job-data-map/q:entry", triggerNode,
      XPathConstants.NODESET);

相关文章