javax.xml.xpath.XPathFactoryConfigurationException#javax.xml.xpath.XPath源码实例Demo

下面列出了javax.xml.xpath.XPathFactoryConfigurationException#javax.xml.xpath.XPath 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: PdfBox-Android   文件: FDFAnnotationPolygon.java
private void initVertices(Element element) throws IOException, NumberFormatException
{
    XPath xpath = XPathFactory.newInstance().newXPath();
    try
    {
        String vertices = xpath.evaluate("vertices", element);
        if (vertices == null || vertices.isEmpty())
        {
            throw new IOException("Error: missing element 'vertices'");
        }
        String[] verticesValues = vertices.split(",");
        float[] values = new float[verticesValues.length];
        for (int i = 0; i < verticesValues.length; i++)
        {
            values[i] = Float.parseFloat(verticesValues[i]);
        }
        setVertices(values);
    }
    catch (XPathExpressionException e)
    {
        Log.d("PdfBox-Android", "Error while evaluating XPath expression for polygon vertices");
    }
}
 
源代码2 项目: SAMLRaider   文件: XMLHelpers.java
/**
 * Removes empty tags, spaces between XML tags
 *
 * @param document
 *            document in which the empty tags should be removed
 */
public void removeEmptyTags(Document document) {
	NodeList nl = null;
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		XPath xPath = XPathFactory.newInstance().newXPath();
		nl = (NodeList) xPath.evaluate("//text()[normalize-space(.)='']", document, XPathConstants.NODESET);
		
		for (int i = 0; i < nl.getLength(); ++i) {
			Node node = nl.item(i);
			node.getParentNode().removeChild(node);
		}
		
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
源代码3 项目: rice   文件: StandardGenericXMLRuleAttribute.java
public List getRuleExtensionValues() {
    List extensionValues = new ArrayList();

    XPath xpath = XPathHelper.newXPath();
    try {
        NodeList nodes = getFields(xpath, getConfigXML(), new String[] { "ALL", "RULE" });
        for (int i = 0; i < nodes.getLength(); i++) {
            Node field = nodes.item(i);
            NamedNodeMap fieldAttributes = field.getAttributes();
            String fieldName = fieldAttributes.getNamedItem("name").getNodeValue();
            Map map = getParamMap();
            if (map != null && !org.apache.commons.lang.StringUtils.isEmpty((String) map.get(fieldName))) {
                RuleExtensionValue value = new RuleExtensionValue();
                value.setKey(fieldName);
                value.setValue((String) map.get(fieldName));
                extensionValues.add(value);
            }
        }
    } catch (XPathExpressionException e) {
        LOG.error("error in getRuleExtensionValues ", e);
        throw new RuntimeException("Error trying to find xml content with xpath expression", e);
    }
    return extensionValues;
}
 
源代码4 项目: proarc   文件: MetsUtils.java
/**
 *
 * Returns a node from the xml document defined by the Xpath
 *
 * @param elements
 * @param xPath
 * @return
 */
public static Node xPathEvaluateNode(List<Element> elements, String xPath) throws MetsExportException {
    Document document = null;
    try {
        document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new MetsExportException("Error while evaluating xPath " + xPath, false, e1);
    }

    for (Element element : elements) {
        Node newNode = element.cloneNode(true);
        document.adoptNode(newNode);
        document.appendChild(newNode);
    }
    XPath xpathObject = XPathFactory.newInstance().newXPath();

    try {
        return (Node) xpathObject.compile(xPath).evaluate(document, XPathConstants.NODE);
    } catch (XPathExpressionException e) {
        throw new MetsExportException("Error while evaluating xPath " + xPath, false, e);
    }
}
 
源代码5 项目: archie   文件: RMQueryContext.java
public <T> List<T> findList(String query) throws XPathExpressionException {
    List<T> result = new ArrayList<T>();

    if (query.equals("/")) {
        result.add((T) rootNode);
    } else {

        String convertedQuery = APathToXPathConverter.convertQueryToXPath(query, firstXPathNode);
        XPath xpath = xPathFactory.newXPath();


        xpath.setNamespaceContext(new ArchieNamespaceResolver(domForQueries));
        NodeList foundNodes = (NodeList) xpath.evaluate(convertedQuery, domForQueries, XPathConstants.NODESET);

        //Perform decoration
        for (int i = 0; i < foundNodes.getLength(); i++) {
            Node node = foundNodes.item(i);
            result.add(getJAXBNode(node));
        }
    }

    return result;
}
 
/**
 * Returns working sets specified in localextensions.xml
 */
public static Set<String> getWorkingSets() {
	Set<String> workingSets = new HashSet<>();
	File localExtensions = new File(PathUtils.getLocalExtensionsPath());
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	try {
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(localExtensions);
		XPath xPath = XPathFactory.newInstance().newXPath();
		String path = "//comment()[following-sibling::*[1][self::extension]]";
		NodeList commentNodes = (NodeList) xPath.compile(path).evaluate(doc, XPathConstants.NODESET);
		for (int i = 0; i < commentNodes.getLength(); i++) {
			Node node = commentNodes.item(i);
			String workingSet = node.getNodeValue().trim();
			workingSets.add(workingSet);
		}
	} catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException e) {
		Activator.logError("Couldn't parse working sets file", e);
	}
	return workingSets;
}
 
源代码7 项目: bdt   文件: HDFSSecUtils.java
public void createSecuredHDFSConnection(String coreSite, String hdfsSite, String krb5Conf, String sslClient, String hdfsHost, String keytabPath, String truststorePath, String realm) throws Exception {
    // Check that ssl-config.xml file provided points to truststore path provided
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(sslClient);

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

    XPathExpression expr = xpath.compile("/configuration/property[name='ssl.client.truststore.location']/value/text()");
    String result = expr.evaluate(doc);

    Assertions.assertThat(result).as("Truststore path specified in ssl-client.xml: " + result + " is different from provided one: " + truststorePath).isEqualTo(truststorePath);

    conf.addResource(new Path("file:///" + coreSite));
    conf.addResource(new Path("file:///" + hdfsSite));

    System.setProperty("java.security.krb5.conf", krb5Conf);

    conf.addResource(new Path("file:///" + sslClient));
    conf.set("fs.defaultFS", "hdfs://" + hdfsHost + "/");

    UserGroupInformation.setConfiguration(conf);
    UserGroupInformation.loginUserFromKeytab("hdfs/" + hdfsHost + "@" + realm, keytabPath);
}
 
源代码8 项目: ci.maven   文件: PluginConfigXmlIT.java
@Test
public void testServerEnvElements() throws Exception {
    File in = new File(CONFIG_XML);
    FileInputStream input = new FileInputStream(in);
    
    // get input XML Document
    DocumentBuilderFactory inputBuilderFactory = DocumentBuilderFactory.newInstance();
    inputBuilderFactory.setIgnoringComments(true);
    inputBuilderFactory.setCoalescing(true);
    inputBuilderFactory.setIgnoringElementContentWhitespace(true);
    inputBuilderFactory.setValidating(false);
    DocumentBuilder inputBuilder = inputBuilderFactory.newDocumentBuilder();
    Document inputDoc = inputBuilder.parse(input);
    
    // parse input XML Document
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "/liberty-plugin-config/serverEnv/text()";
    String nodeValue = (String) xPath.compile(expression).evaluate(inputDoc, XPathConstants.STRING);
    File f1 = new File(SOURCE_SERVER_ENV);
    File f2 = new File(nodeValue);
    assertEquals("serverEnv value", f1.getAbsolutePath(), f2.getAbsolutePath());
    assertEquals("verify target server server.env", FileUtils.fileRead(f2),
            FileUtils.fileRead(TARGET_SERVER_ENV));
}
 
源代码9 项目: xframium-java   文件: XMLPageDataProvider.java
/**
 * Gets the nodes.
 *
 * @param xmlDocument the xml document
 * @param xPathExpression the x path expression
 * @return the nodes
 */
private NodeList getNodes( Document xmlDocument, String xPathExpression )
{
	try
	{
		if (log.isDebugEnabled())
			log.debug( "Attempting to return Nodes for [" + xPathExpression + "]" );

		XPath xPath = xPathFactory.newXPath();
		return ( NodeList ) xPath.evaluate( xPathExpression, xmlDocument, XPathConstants.NODESET );
	}
	catch (Exception e)
	{
		log.error( "Error parsing xPath Expression [" + xPathExpression + "]" );
		return null;
	}
}
 
源代码10 项目: cerberus-source   文件: Differences.java
/**
 * Creates a {@link Differences} instance from the given {@link Document}
 * 
 * @param documentDiff
 *            the {@link Document} base to create the {@link Differences} instance
 * @return a {@link Differences} instance from the given {@link Document}
 * @throws DifferencesException
 *             if the given {@link Document} does not have a correct {@link Differences} format
 */
public static Differences fromDocument(Document documentDiff) throws DifferencesException {
	NodeList list = null;
	try {
		XPath path = XPathFactory.newInstance().newXPath();
		list = (NodeList) path.compile(DIFFERENCE_COMMON_XPATH).evaluate(documentDiff, XPathConstants.NODESET);
	} catch (XPathExpressionException e) {
		throw new DifferencesException(e);
	}

	Differences diff = new Differences();
	for (int i = 0; i < list.getLength(); i++) {
		diff.addDifference(new Difference(list.item(i).getFirstChild().getNodeValue()));
	}
	return diff;
}
 
源代码11 项目: openjdk-jdk9   文件: Bug4991939.java
@Test
public void testXPath13() throws Exception {
    QName qname = new QName(XMLConstants.XML_NS_URI, "");

    XPathFactory xpathFactory = XPathFactory.newInstance();
    Assert.assertNotNull(xpathFactory);

    XPath xpath = xpathFactory.newXPath();
    Assert.assertNotNull(xpath);

    try {
        xpath.evaluate("1+1", (Object) null, qname);
        Assert.fail("failed , expected IAE not thrown");
    } catch (IllegalArgumentException e) {
        ; // as expected
    }
}
 
源代码12 项目: MtgDesktopCompanion   文件: PackagesProvider.java
public List<MagicEdition> listEditions() {

		if (!list.isEmpty())
			return list;

		try {
			XPath xPath = XPathFactory.newInstance().newXPath();
			String expression = "//edition/@id";
			NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
			for (int i = 0; i < nodeList.getLength(); i++)
			{
				list.add(MTGControler.getInstance().getEnabled(MTGCardsProvider.class).getSetById(nodeList.item(i).getNodeValue()));
			}
			
			Collections.sort(list);
		} catch (Exception e) {
			logger.error("Error retrieving IDs ", e);
		}
		return list;
	}
 
源代码13 项目: openjdk-jdk9   文件: Bug4992805.java
private XPath createXPath() throws XPathFactoryConfigurationException {
    XPathFactory xpathFactory = XPathFactory.newInstance();
    Assert.assertNotNull(xpathFactory);
    XPath xpath = xpathFactory.newXPath();
    Assert.assertNotNull(xpath);
    return xpath;
}
 
源代码14 项目: mycore   文件: MCRXMLFunctions.java
/**
 * The method return a org.w3c.dom.NodeList as subpath of the doc input
 * NodeList selected by a path as String.
 *
 * @param doc
 *            the input org.w3c.dom.Nodelist
 * @param path
 *            the path of doc as String
 * @return a subpath of doc selected by path as org.w3c.dom.NodeList
 */
public static NodeList getTreeByPath(NodeList doc, String path) {
    NodeList n = null;
    DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
    try {
        // build path selection
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(path);
        // select part
        Document document = documentBuilder.newDocument();
        if (doc.item(0).getNodeName().equals("#document")) {
            // LOGGER.debug("NodeList is a document.");
            Node child = doc.item(0).getFirstChild();
            if (child != null) {
                Node node = doc.item(0).getFirstChild();
                Node imp = document.importNode(node, true);
                document.appendChild(imp);
            } else {
                document.appendChild(doc.item(0));
            }
        }
        n = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    } catch (Exception e) {
        LOGGER.error("Error while getting tree by path {}", path, e);
    } finally {
        MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
    }
    return n;
}
 
public void removePersonObjects( Document doc ) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression personProperties = null;
    try {
        personProperties = xpath.compile("//*[@class='org.kuali.rice.kim.impl.identity.PersonImpl']");
        NodeList matchingNodes = (NodeList)personProperties.evaluate( doc, XPathConstants.NODESET );
        for(int i = 0; i < matchingNodes.getLength(); i++) {
            Node tempNode = matchingNodes.item(i);
            tempNode.getParentNode().removeChild(tempNode);
        }
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
}
 
源代码16 项目: BotLibre   文件: Test.java
public static void testXPath() throws Exception {
	//String html = Utils.httpGET("http://www.google.ru/search?q=site::http://endurancerobots.com/+робот");
	//System.out.println(html);
		
	Bot bot = Bot.createInstance();
	Http http = bot.awareness().getSense(Http.class);
	
	Element element = http.parseURL(new URL("http://ab-w.net/HTML5/html5_em.php"));
	System.out.println(element.getTextContent());
	XPathFactory factory = XPathFactory.newInstance();
	XPath path = factory.newXPath();
	Object node = path.evaluate("//*/p[5]/em/text()", element, XPathConstants.NODE);
	System.out.println(((Text)node).getTextContent());
	System.out.println("курсивный");
}
 
源代码17 项目: hawkular-apm   文件: XML.java
/**
 * This method evaluates the xpath expression on the supplied
 * node. The result can either be a document fragment, a
 * text node value or null if the expression references a
 * missing part of the document.
 *
 * @param xpath The xpath expression
 * @param node The node
 * @return The result, or null if not found (which may be due to an expression error)
 */
public static String evaluate(String xpath, Object node) {
    Node domNode = getNode(node);

    if (domNode == null) {
        log.severe("Unable to evaluate non DOM Node object");
        return null;
    }

    // If no xpath expression, then serialize
    if (xpath == null || xpath.trim().isEmpty()) {
        return serialize(node);
    }

    // TODO: HWKBTM-104 Investigate caching compiled xpath expressions
    try {
        xpath = getExpression(xpath);
        XPath xp = XPathFactory.newInstance().newXPath();
        Node result = (Node) xp.evaluate(xpath, domNode, XPathConstants.NODE);

        if (result != null) {
            if (result.getNodeType() == Node.TEXT_NODE) {
                return result.getNodeValue();
            } else if (result.getNodeType() == Node.ATTRIBUTE_NODE) {
                return result.getNodeValue();
            }
            return serialize(result);
        }
    } catch (DOMException|XPathExpressionException e) {
        log.log(Level.SEVERE, "Failed to evaluate xpath '" + xpath + "'", e);
    }

    return null;
}
 
源代码18 项目: development   文件: XMLConverter.java
/**
 * 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);
}
 
源代码19 项目: development   文件: XMLConverter.java
/**
 * 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);
}
 
源代码20 项目: BotLibre   文件: Http.java
/**
 * Post the XML document object and return the XML data from the URL.
 */
public Vertex postXMLAuth(String url, String user, String password, String agent, Vertex xmlObject, String xpath, Network network) {
	log("POST XML Auth", Level.INFO, url);
	try {
		String data = convertToXML(xmlObject);
		log("POST XML", Level.FINE, data);
		String xml = Utils.httpAuthPOST(url, user, password, agent, "application/xml", data);
		log("XML", Level.FINE, xml);
		InputStream stream = new ByteArrayInputStream(xml.getBytes("utf-8"));
		Element element = parseXML(stream);
		if (element == null) {
			return null;
		}
		XPathFactory factory = XPathFactory.newInstance();
		XPath path = factory.newXPath();
		Object node = path.evaluate(xpath, element, XPathConstants.NODE);
		if (node instanceof Element) {
			return convertElement((Element)node, network);
		} else if (node instanceof Attr) {
			return network.createVertex(((Attr)node).getValue());
		} else if (node instanceof org.w3c.dom.Text) {
			return network.createVertex(((org.w3c.dom.Text)node).getTextContent());
		}
		return null;
	} catch (Exception exception) {
		log(exception);
		return null;
	}
}
 
源代码21 项目: Knowage-Server   文件: XmlDataReader.java
private NodeList readXMLNodes(Document doc, String xpathExpression) throws Exception {
	XPath xpath = XPathFactory.newInstance().newXPath();
	XPathExpression expr = xpath.compile(xpathExpression);

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

	return nodes;
}
 
源代码22 项目: milkman   文件: XmlContentType.java
public static String toPrettyString(String xml, int indent) {
    try {
        // Turn xml string into a document
        Document document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

        // Remove whitespaces outside tags
        document.normalize();
        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']",
                                                      document,
                                                      XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        log.warn("Failed to format xml", e);
    }
    return xml;
}
 
源代码23 项目: SB_Elsinore_Server   文件: BeerXMLReader.java
/**
 * Add a mash Profile to a recipe.
 * @param recipe The @{Recipe} object to add the mash profile to.
 * @param mashProfile The node containing the beerXML Mash element.
 * @param xp an XPath object to use to run XPath expressions.
 * @throws XPathException If an XPath expression could not be run.
 */
private void parseMashProfile(Recipe recipe, Node mashProfile, XPath xp) throws XPathException {
    String name = getString(mashProfile, "NAME", xp);
    double grainTemp = getDouble(mashProfile, "GRAIN_TEMP", xp);
    Node mashSteps = (Node) xp.evaluate("MASH_STEPS", mashProfile, XPathConstants.NODE);
    String notes = getString(mashProfile, "NOTES", xp);
    double tunTemp = getDouble(mashProfile, "TUN_TEMP", xp);
    double spargeTemp = getDouble(mashProfile, "SPARGE_TEMP", xp);
    double ph = getDouble(mashProfile, "PH", xp);
    double tunWeight = getDouble(mashProfile, "TUN_WEIGHT", xp);
    double tunSpecificHeat = getDouble(mashProfile, "TUN_SPECIFIC_HEAT", xp);
    boolean tunAdjust = getBoolean(mashProfile, "TUN_ADJUST", xp, false);

    Mash mash = recipe.getMash();
    if (mash == null) {
        mash = new Mash(name, recipe);
        recipe.setMash(mash);
    } else {
        mash.setName(name);
    }

    mash.setGrainTemp(grainTemp);
    mash.setNotes(notes);
    mash.setTunTemp(tunTemp);
    mash.setSpargeTemp(spargeTemp);
    mash.setPh(ph);
    mash.setTunWeight(tunWeight);
    mash.setTunSpecificHeat(tunSpecificHeat);
    mash.setTunAdjust(tunAdjust);
    mash.setTunWeight(getString(mashProfile, "DISPLAY_TUN_WEIGHT", xp));
    mash.setMashTempUnits(getString(mashProfile, "DISPLAY_GRAIN_TEMP", xp));

    parseMashSteps(mash, mashSteps, xp);
}
 
源代码24 项目: rice   文件: XPathTest.java
@Test
public void testXPathWithNamespaceAwareDOM() throws Exception {
    Document doc = getDocument(true, false);
    XPath xpath = getXPath(null);
    String channelName = (String) xpath.evaluate("/nreq:notification/nreq:channel", doc.getDocumentElement(), XPathConstants.STRING);
    assertEquals("Test Channel #1", channelName);
}
 
源代码25 项目: SAMLRaider   文件: XMLHelpers.java
/**
 * Sign whole SAML Message
 *
 * @param document
 *            Document with the response to sign
 * @param signAlgorithm
 *            Signature algorithm in uri form, default if an unknown
 *            algorithm is provided:
 *            http://www.w3.org/2001/04/xmldsig-more#rsa-sha256
 * @param digestAlgorithm
 *            Digest algorithm in uri form, default if an unknown algorithm
 *            is provided: http://www.w3.org/2001/04/xmlenc#sha256
 */
public void signMessage(Document document, String signAlgorithm, String digestAlgorithm, X509Certificate cert, PrivateKey key)
		throws CertificateException, FileNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException,
		MarshalException, XMLSignatureException, IOException {
	try {
		if(Thread.currentThread().getContextClassLoader() == null){
			Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); 
		}
		setIDAttribute(document);
		XPath xpath = XPathFactory.newInstance().newXPath();
		XPathExpression expr = xpath.compile("//*[local-name()='Response']/@ID");
		NodeList nlURIs = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

		String[] sigIDs = new String[nlURIs.getLength()];

		for (int i = 0; i < nlURIs.getLength(); i++) {
			sigIDs[i] = nlURIs.item(i).getNodeValue();
		}

		Init.init();
		for (String id : sigIDs) {
			signElement(document, id, cert, key, signAlgorithm, digestAlgorithm);
		}
	} catch (XPathExpressionException e) {
		e.printStackTrace();
	}
}
 
源代码26 项目: AuTe-Framework   文件: XMLUtils.java
/**
 * Parse XML document and get value using XPath expression.
 *
 * @param source          original document
 * @param xpathExpression valid XPath expression for getting required value
 * @return string value by xpath expression
 */
@SuppressWarnings("WeakerAccess")
public static String getValueByXPath(String source, String xpathExpression) throws Exception {
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(new InputSource(new StringReader(source)));
    XPath xPath = XPathFactory.newInstance().newXPath();
    return xPath.compile(xpathExpression).evaluate(xmlDocument);
}
 
源代码27 项目: buck   文件: WorkspaceUpdater.java
private static Node findChangeListManagerNode(XPath xpath, Document workspaceDocument)
    throws XPathExpressionException {
  return (Node)
      xpath
          .compile("/project/component[@name = 'ChangeListManager']")
          .evaluate(workspaceDocument, XPathConstants.NODE);
}
 
源代码28 项目: ph-commons   文件: XPathHelper.java
/**
 * Create a new {@link XPath} with the passed namespace context using the
 * default {@link XPathFactory}.
 *
 * @param aNamespaceContext
 *        Namespace context to be used. May be <code>null</code>.
 * @return The created non-<code>null</code> {@link XPath} object
 */
@Nonnull
public static XPath createNewXPath (@Nullable final NamespaceContext aNamespaceContext)
{
  return createNewXPath (s_aXPathFactory,
                         (XPathVariableResolver) null,
                         (XPathFunctionResolver) null,
                         aNamespaceContext);
}
 
源代码29 项目: rice   文件: XPathSearchableAttribute.java
@Override
public List<DocumentAttribute> extractDocumentAttributes(@WebParam(name = "extensionDefinition") ExtensionDefinition extensionDefinition,
                                                         @WebParam(name = "documentWithContent") DocumentWithContent documentWithContent) {
    List<DocumentAttribute> attribs = new ArrayList<DocumentAttribute>(1);
    String appContent = documentWithContent.getDocumentContent().getApplicationContent();
    XPath xpath = XPathHelper.newXPath();
    try {
        //InputSource source = new StringReader(appContent);
        Element source = DocumentBuilderFactory
                .newInstance().newDocumentBuilder().parse(new InputSource(new BufferedReader(new StringReader(appContent)))).getDocumentElement();
        String result = (String) xpath.evaluate(xpathExpression, source, XPathConstants.STRING);
        // xpath has no concept of null node, missing text values are the empty string
        if (StringUtils.isNotEmpty(result)) {
            try {
                attribs.add(createAttribute(this.key, result, this.dataType));
            } catch (ParseException pe) {
                log.error("Error converting value '" + result + "' to type '" + this.dataType + "'");
            }
        }
    } catch (XPathExpressionException xep) {
        log.error("Error evaluating searchable attribute expression: '" + this.xpathExpression + "'", xep);
    } catch (SAXException se) {
        log.error("Error parsing application content: '" + appContent + "'", se);
    } catch (ParserConfigurationException pce) {
        log.error("Error parsing application content: '" + appContent + "'", pce);
    } catch (IOException ioe) {
        log.error("Error parsing application content: '" + appContent + "'", ioe);
    }
    return attribs;
}
 
源代码30 项目: ToGoZip   文件: TranslationStatistics.java
private static XPathExpression getStringsXPathExpression(String expression) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    XPathExpression stringNodesExpression = null;
    try {
        stringNodesExpression = xpath.compile(expression);
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    }
    return stringNodesExpression;
}