当前位置: 首页>>代码示例>>Java>>正文


Java XPath.compile方法代码示例

本文整理汇总了Java中javax.xml.xpath.XPath.compile方法的典型用法代码示例。如果您正苦于以下问题:Java XPath.compile方法的具体用法?Java XPath.compile怎么用?Java XPath.compile使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在javax.xml.xpath.XPath的用法示例。


在下文中一共展示了XPath.compile方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: isMavenFXProject

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
public static boolean isMavenFXProject(@NonNull final Project prj) {
    if (isMavenProject(prj)) {
        try {
            FileObject pomXml = prj.getProjectDirectory().getFileObject("pom.xml"); //NOI18N
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(FileUtil.toFile(pomXml));
            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression exprJfxrt = xpath.compile("//bootclasspath[contains(text(),'jfxrt')]"); //NOI18N
            XPathExpression exprFxPackager = xpath.compile("//executable[contains(text(),'javafxpackager')]"); //NOI18N
            XPathExpression exprPackager = xpath.compile("//executable[contains(text(),'javapackager')]"); //NOI18N
            boolean jfxrt = (Boolean) exprJfxrt.evaluate(doc, XPathConstants.BOOLEAN);
            boolean packager = (Boolean) exprPackager.evaluate(doc, XPathConstants.BOOLEAN);
            boolean fxPackager = (Boolean) exprFxPackager.evaluate(doc, XPathConstants.BOOLEAN);
            return jfxrt && (packager || fxPackager);
        } catch (XPathExpressionException | ParserConfigurationException | SAXException | IOException ex) {
            LOGGER.log(Level.INFO, "Error while parsing pom.xml.", ex);  //NOI18N
            return false;
        }
    }
    return false;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:24,代码来源:JFXProjectUtils.java

示例2: getNodeList

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
public static Iterator<Node> getNodeList(String exp, Element dom) throws XPathExpressionException {
	XPath xpath = XPathFactory.newInstance().newXPath();
	XPathExpression expUserTask = xpath.compile(exp);
	final NodeList nodeList = (NodeList) expUserTask.evaluate(dom, XPathConstants.NODESET);

	return new Iterator<Node>() {
		private int index = 0;

		@Override
		public Node next() {
			return nodeList.item(index++);
		}

		@Override
		public boolean hasNext() {
			return (nodeList.getLength() - index) > 0;
		}
	};
}
 
开发者ID:DataAgg,项目名称:DAFramework,代码行数:20,代码来源:DomXmlUtils.java

示例3: getMaxRId

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray()));
		XPathFactory xPathfactory = XPathFactory.newInstance();
		XPath xpath = xPathfactory.newXPath();
		XPathExpression expr = xpath.compile("Relationships/*");
		NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
		for (int i = 0; i < nodeList.getLength(); i++) {
			String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent();
			int idNum = Integer.parseInt(id.substring("rId".length()));
			this.maxRId = idNum > this.maxRId ? idNum : this.maxRId;
		}
		return this.maxRId;
	}
 
开发者ID:dvbern,项目名称:doctemplate,代码行数:17,代码来源:DOCXMergeEngine.java

示例4: countNodes

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
/**
 * Count nodes which are given via xpath expression
 */
public static Double countNodes(Node node, String nodePath)
        throws XPathExpressionException {
    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    final XPathExpression expr = xpath.compile("count(" + nodePath + ')');
    return (Double) expr.evaluate(node, XPathConstants.NUMBER);
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:11,代码来源:XMLConverter.java

示例5: getCoordinates

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
/**@param{Object} Address- The physical address of a location
  * This method returns Geocode coordinates of the Address object.Geocoding is the process of converting addresses (like "1600 Amphitheatre Parkway,
  * Mountain View, CA") into geographic coordinates (like latitude 37.423021 and longitude -122.083739).Please give all the physical Address values 
  * for a precise coordinate. setting none of the values will give a null value for the Latitude and Longitude. 
  */ 
public static GeoCode getCoordinates(Address address) throws Exception
 {
  GeoCode geo= new GeoCode();
  String physicalAddress = (address.getAddress1() == null ? "" : address.getAddress1() + ",")
		  + (address.getAddress2() == null ? "" : address.getAddress2() + ",")
		  + (address.getCityName() == null ? "" : address.getCityName() + ",")
		  + (address.getState()    == null ? "" : address.getState() + "-")
		  + (address.getZip()      == null ? "" : address.getZip() + ",")
		  + (address.getCountry()  == null ? "" :  address.getCountry());
  String api = GMAPADDRESS + URLEncoder.encode(physicalAddress, "UTF-8") + SENSOR;
  URL url = new URL(api);
  HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
  httpConnection.connect();
  int responseCode = httpConnection.getResponseCode();
  if(responseCode == 200)
   {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(httpConnection.getInputStream());
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(STATUS);
    String status = (String)expr.evaluate(document, XPathConstants.STRING);
    if(status.equals("OK"))
     {
       expr = xpath.compile(LATITUDE);
       String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
          expr = xpath.compile(LONGITUDE);
       String longitude = (String)expr.evaluate(document, XPathConstants.STRING);
       geo.setLatitude(latitude);
       geo.setLongitude(longitude);
     }
    }
    else
    {
    	throw new Exception("Fail to Convert to Geocode");
    }
	return geo;
  }
 
开发者ID:Code4SocialGood,项目名称:c4sg-services,代码行数:44,代码来源:CoordinatesUtil.java

示例6: queryApi

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
/**Query the API and returns the list of expansions. Update the cache.
 * @param abbrev lowercase abbreviation.
 * @throws Exception
 */
private synchronized String[] queryApi(String abbrev, int retryLeft)
		throws Exception {
	if (retryLeft < MAX_RETRY)
		Thread.sleep(1000);
	URL url = new URL(String.format("%s?uid=%s&tokenid=%s&term=%s",
			API_URL, uid, tokenId, URLEncoder.encode(abbrev, "utf8")));

	boolean cached = abbrToExpansion.containsKey(abbrev);
	LOG.info("{} {}", cached ? "<cached>" : "Querying", url);
	if (cached) return abbrToExpansion.get(abbrev);


	HttpURLConnection connection = (HttpURLConnection) url
				.openConnection();
	connection.setConnectTimeout(0);
	connection.setRequestProperty("Accept", "*/*");
	connection
	.setRequestProperty("Content-Type", "multipart/form-data");

	connection.setUseCaches(false);

	if (connection.getResponseCode() != 200) {
		Scanner s = new Scanner(connection.getErrorStream())
				.useDelimiter("\\A");
		LOG.error("Got HTTP error {}. Message is: {}",
				connection.getResponseCode(), s.next());
		s.close();
		throw new RuntimeException("Got response code:"
				+ connection.getResponseCode());
	}

	DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
	Document doc;
	try {
		doc = builder.parse(connection.getInputStream());
	} catch (IOException e) {
		LOG.error("Got error while querying: {}", url);
		throw e;
	}

	XPathFactory xPathfactory = XPathFactory.newInstance();
	XPath xpath = xPathfactory.newXPath();
	XPathExpression resourceExpr = xpath.compile("//definition/text()");

	NodeList resources = (NodeList) resourceExpr.evaluate(doc,
			XPathConstants.NODESET);

	Vector<String> resVect = new Vector<>();
	for (int i=0; i<resources.getLength(); i++){
		String expansion = resources.item(i).getTextContent().replace(String.valueOf((char) 160), " ").trim();
		if (!resVect.contains(expansion))
			resVect.add(expansion);
	}
	
	String[] res = resVect.toArray(new String[]{});
	abbrToExpansion.put(abbrev, res);
	increaseFlushCounter();
	return res;
}
 
开发者ID:marcocor,项目名称:smaph,代码行数:64,代码来源:Stands4AbbreviationExpansion.java

示例7: test07

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
@Test(dataProvider = "document")
public void test07(XPath xpath, Document doc) throws XPathExpressionException {
    XPathExpression exp = xpath.compile("/Customers/Customer");
    XPathNodes nodes = exp.evaluateExpression(doc, XPathNodes.class);
    assertTrue(nodes.size() == 3);
    for (Node n : nodes) {
        assertEquals(n.getLocalName(), "Customer");
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:XPathExpAnyTypeTest.java

示例8: MetaDataMerger

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
public MetaDataMerger ( final String label, final boolean compressed ) throws Exception
{
    this.doc = createDocument ();

    final XPathFactory xpf = XPathFactory.newInstance ();
    final XPath xp = xpf.newXPath ();
    this.isCategoryPathExpression = xp.compile ( "properties/property[@name='org.eclipse.equinox.p2.type.category']/@value" );

    final ProcessingInstruction pi = this.doc.createProcessingInstruction ( "metadataRepository", "" );
    pi.setData ( "version=\"1.1.0\"" );
    this.doc.appendChild ( pi );

    this.r = this.doc.createElement ( "repository" );
    this.doc.appendChild ( this.r );
    this.r.setAttribute ( "name", label );
    this.r.setAttribute ( "type", "org.eclipse.equinox.internal.p2.metadata.repository.LocalMetadataRepository" );
    this.r.setAttribute ( "version", "1" );

    this.p = this.doc.createElement ( "properties" );
    this.r.appendChild ( this.p );

    addProperty ( this.p, "p2.compressed", "" + compressed );
    addProperty ( this.p, "p2.timestamp", "" + System.currentTimeMillis () );

    this.u = this.doc.createElement ( "units" );
    this.r.appendChild ( this.u );
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:28,代码来源:MetaDataMerger.java

示例9: getNodeByXPath

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
/**
 * Returns the node in the given document at the specified XPath.
 * 
 * @param node
 *            The document to be checked.
 * @param xpathString
 *            The xpath to look at.
 * @return The node at the given xpath.
 * @throws XPathExpressionException
 */
public static Node getNodeByXPath(Node node, String xpathString)
        throws XPathExpressionException {

    final XPathFactory factory = XPathFactory.newInstance();
    final XPath xpath = factory.newXPath();
    xpath.setNamespaceContext(new XmlNamespaceResolver(
            getOwningDocument(node)));
    final XPathExpression expr = xpath.compile(xpathString);
    return (Node) expr.evaluate(node, XPathConstants.NODE);
}
 
开发者ID:servicecatalog,项目名称:oscm,代码行数:21,代码来源:XMLConverter.java

示例10: transform

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
private String transform(Document document) throws Exception {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    XPathExpression testNameExpression = xpath.compile("//test-case/name");
    NodeList testNameNodes = (NodeList) testNameExpression.evaluate(document, XPathConstants.NODESET);
    for (int i = 0; i < testNameNodes.getLength(); i++) {
        testNameNodes.item(i).getFirstChild().setNodeValue(testNameNodes.item(i).getTextContent().replace("'", ""));
    }
 String xmlAfterTransform = Util.getXMLFile(document);
 return xmlAfterTransform;
}
 
开发者ID:Esprizzle,项目名称:allure-report-processor,代码行数:12,代码来源:AllureReportProcessor.java

示例11: getChildNodesByExpression

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
public static NodeList getChildNodesByExpression(Document doc, String expression) {
  try {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile(expression);

    Object result = expr.evaluate(doc, XPathConstants.NODESET);
    return (NodeList) result;

  } catch (Exception ex) {
    ex.printStackTrace();
  }
  return null;
}
 
开发者ID:comtel2000,项目名称:fritz-home-skill,代码行数:14,代码来源:XmlUtils.java

示例12: removeNode

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
private void removeNode(Document document, String xpathStr) throws Exception {
	XPathFactory xpf = XPathFactory.newInstance();
	XPath xpath = xpf.newXPath();
	XPathExpression expression = xpath.compile(xpathStr);
	Node node = (Node) expression.evaluate(document, XPathConstants.NODE);
	node.getParentNode().removeChild(node);
}
 
开发者ID:Esprizzle,项目名称:allure-report-processor,代码行数:8,代码来源:AllureReportProcessor.java

示例13: test12

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
@Test(dataProvider = "document")
public void test12(XPath xpath, Document doc) throws XPathExpressionException {
    XPathExpression exp = xpath.compile("string(/Customers/Customer[@id=3]/Phone/text())");
    XPathEvaluationResult<?> result = exp.evaluateExpression(doc, XPathEvaluationResult.class);
    verifyResult(result, "3333333333");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:7,代码来源:XPathExpAnyTypeTest.java

示例14: generateFiles

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
private static void generateFiles(File parentDir, String testName, int byteIndex, byte[] template, String matchXPath) throws Exception {
    File testDir = new File(parentDir, testName);
    if(!testDir.exists() && !testDir.mkdirs()) {
        throw new RuntimeException("Error creating directory " + testDir.getAbsolutePath());
    }

    // Initialize the heavy weight XML stuff.
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    XPathExpression expr = xpath.compile(matchXPath);

    // Iterate over all possible value the current byte could have.
    for(int i = 0; i <= 255; i++) {

        // Generate a packet.
        byte[] copy = Arrays.copyOf(template, template.length);
        copy[byteIndex] = (byte) i;
        File output = new File(testDir, i + ".pcapng");
        FileUtils.writeByteArrayToFile(output, copy);

        // Use WireShark to decode the packet to an xml form.
        File decodedOutput = new File(testDir, i + ".xml");
        ProcessBuilder pb = new ProcessBuilder("tshark", "-T", "pdml", "-r", output.getAbsolutePath());
        pb.redirectOutput(ProcessBuilder.Redirect.to(decodedOutput));
        Process process = pb.start();
        process.waitFor();

        // Check if a given XPath is found -> A valid parameter was found.
        Document document = builder.parse(decodedOutput);
        NodeList list= (NodeList) expr.evaluate(document, XPathConstants.NODESET);

        // If a valid parameter is found, output that to the console.
        if(list.getLength() > 0) {
            String name = list.item(0).getAttributes().getNamedItem("showname").getNodeValue();
            String value = list.item(0).getAttributes().getNamedItem("value").getNodeValue();
            System.out.println("found option for " + testName + ": " + name + " = 0x" + value);
        }
    }
}
 
开发者ID:apache,项目名称:incubator-plc4x,代码行数:43,代码来源:PcapGenerator.java

示例15: test03

import javax.xml.xpath.XPath; //导入方法依赖的package包/类
@Test(dataProvider = "xpath")
public void test03(XPath xpath) throws XPathExpressionException {
    XPathExpression exp = xpath.compile("1+1");
    int result = exp.evaluateExpression((Object)null, Integer.class);
    assertTrue(result == 2);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:7,代码来源:XPathExpAnyTypeTest.java


注:本文中的javax.xml.xpath.XPath.compile方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。