javax.xml.xpath.XPathExpression Java Examples
The following examples show how to use
javax.xml.xpath.XPathExpression.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XPathImpl.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * <p>Compile an XPath expression for later evaluation.</p> * * <p>If <code>expression</code> contains any {@link XPathFunction}s, * they must be available via the {@link XPathFunctionResolver}. * An {@link XPathExpressionException} will be thrown if the <code>XPathFunction</code> * cannot be resovled with the <code>XPathFunctionResolver</code>.</p> * * <p>If <code>expression</code> is <code>null</code>, a <code>NullPointerException</code> is thrown.</p> * * @param expression The XPath expression. * * @return Compiled XPath expression. * @throws XPathExpressionException If <code>expression</code> cannot be compiled. * @throws NullPointerException If <code>expression</code> is <code>null</code>. */ public XPathExpression compile(String expression) throws XPathExpressionException { if ( expression == null ) { String fmsg = XSLMessages.createXPATHMessage( XPATHErrorResources.ER_ARG_CANNOT_BE_NULL, new Object[] {"XPath expression"} ); throw new NullPointerException ( fmsg ); } try { com.sun.org.apache.xpath.internal.XPath xpath = new XPath (expression, null, prefixResolver, com.sun.org.apache.xpath.internal.XPath.SELECT ); // Can have errorListener XPathExpressionImpl ximpl = new XPathExpressionImpl (xpath, prefixResolver, functionResolver, variableResolver, featureSecureProcessing, useServiceMechanism, featureManager ); return ximpl; } catch ( javax.xml.transform.TransformerException te ) { throw new XPathExpressionException ( te ) ; } }
Example #2
Source File: ManifestParser.java From NBANDROID-V2 with Apache License 2.0 | 6 votes |
private static Iterable<String> getAttrNames(InputStream is, XPathExpression expr) { Set<String> names = Sets.newHashSet(); if (expr != null) { try { Document doc = parseStream(is); if (doc != null) { NodeList nodelist = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodelist.getLength(); i++) { String name = nodelist.item(i).getNodeValue(); names.add(name); } } } catch (XPathExpressionException ex) { LOG.log(Level.WARNING, null, ex); } } return names; }
Example #3
Source File: XPathHelper.java From ph-commons with Apache License 2.0 | 6 votes |
/** * Create a new XPath expression for evaluation. * * @param aXPath * The pre-created XPath object. May not be <code>null</code>. * @param sXPath * The main XPath string to be evaluated * @return The {@link XPathExpression} object to be used. * @throws IllegalArgumentException * if the XPath cannot be compiled */ @Nonnull public static XPathExpression createNewXPathExpression (@Nonnull final XPath aXPath, @Nonnull @Nonempty final String sXPath) { ValueEnforcer.notNull (aXPath, "XPath"); ValueEnforcer.notNull (sXPath, "XPathExpression"); try { return aXPath.compile (sXPath); } catch (final XPathExpressionException ex) { throw new IllegalArgumentException ("Failed to compile XPath expression '" + sXPath + "'", ex); } }
Example #4
Source File: XPathImpl.java From JDKSourceCode1.8 with MIT License | 6 votes |
/** * <p>Compile an XPath expression for later evaluation.</p> * * <p>If <code>expression</code> contains any {@link XPathFunction}s, * they must be available via the {@link XPathFunctionResolver}. * An {@link XPathExpressionException} will be thrown if the <code>XPathFunction</code> * cannot be resovled with the <code>XPathFunctionResolver</code>.</p> * * <p>If <code>expression</code> is <code>null</code>, a <code>NullPointerException</code> is thrown.</p> * * @param expression The XPath expression. * * @return Compiled XPath expression. * @throws XPathExpressionException If <code>expression</code> cannot be compiled. * @throws NullPointerException If <code>expression</code> is <code>null</code>. */ public XPathExpression compile(String expression) throws XPathExpressionException { if ( expression == null ) { String fmsg = XSLMessages.createXPATHMessage( XPATHErrorResources.ER_ARG_CANNOT_BE_NULL, new Object[] {"XPath expression"} ); throw new NullPointerException ( fmsg ); } try { com.sun.org.apache.xpath.internal.XPath xpath = new XPath (expression, null, prefixResolver, com.sun.org.apache.xpath.internal.XPath.SELECT ); // Can have errorListener XPathExpressionImpl ximpl = new XPathExpressionImpl(xpath, prefixResolver, functionResolver, variableResolver, featureSecureProcessing, featureManager ); return ximpl; } catch ( javax.xml.transform.TransformerException te ) { throw new XPathExpressionException ( te ) ; } }
Example #5
Source File: XmlSignature.java From cstc with GNU General Public License v3.0 | 6 votes |
protected void validateIdAttributes(Document doc) throws Exception { String idAttribute = new String(idIdentifier.getText()); if( idAttribute == null || idAttribute.isEmpty() ) { return; } XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("descendant-or-self::*/@" + idAttribute); NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); if(nodeList != null && nodeList.getLength() > 0) { for(int j = 0; j < nodeList.getLength(); j++) { Attr attr = (Attr)nodeList.item(j); ((Element)attr.getOwnerElement()).setIdAttributeNode(attr,true); } } }
Example #6
Source File: ProvidedSigningCertificateAndNoCertTest.java From dss with GNU Lesser General Public License v2.1 | 6 votes |
private DSSDocument removeKeyInfo(DSSDocument signedDoc) { Document dom = DomUtils.buildDOM(signedDoc); try { Element root = dom.getDocumentElement(); XPathExpression xpath = DomUtils.createXPathExpression(XMLDSigPaths.KEY_INFO_PATH); Element keyInfoTag = (Element) xpath.evaluate(root, XPathConstants.NODE); keyInfoTag.getParentNode().removeChild(keyInfoTag); } catch (Exception e) { throw new DSSException("Unable to remove the KeyInfo element", e); } byte[] bytes = DSSXMLUtils.serializeNode(dom); final InMemoryDocument inMemoryDocument = new InMemoryDocument(bytes); inMemoryDocument.setName("bla.xml"); inMemoryDocument.setMimeType(MimeType.XML); return inMemoryDocument; }
Example #7
Source File: WSDL11SOAPOperationExtractor.java From carbon-apimgt with Apache License 2.0 | 6 votes |
private Node findFirstElementByName(String name, Document doc) { XPathFactory xpathfactory = XPathFactory.newInstance(); XPath xpath = xpathfactory.newXPath(); try { XPathExpression expr = xpath.compile("//*[@name='" + name + "']"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; if (nodes == null || nodes.getLength() < 1) { return null; } return nodes.item(0); } catch (XPathExpressionException e) { log.error("Error occurred while finding element " + name + "in given document", e); return null; } }
Example #8
Source File: Utils.java From micro-integrator with Apache License 2.0 | 6 votes |
/** * retrieve the value for the given xpath from the file * * @param element element * @param xPath xpath * @return value from xpath */ public static String getValueFromXPath(Element element, String xPath) { String nodeValue = null; try { XPathFactory xpf = XPathFactory.newInstance(); XPath xp = xpf.newXPath(); XPathExpression xPathExpression = xp.compile(xPath); Node text = (Node) xPathExpression.evaluate(element, XPathConstants.NODE); if (text != null) { nodeValue = text.getTextContent(); } } catch (XPathExpressionException e) { throw new SecureVaultException("Error reading primary key Store details from carbon.xml file ", e); } return nodeValue; }
Example #9
Source File: XPathEvaluator.java From DAFramework with MIT License | 6 votes |
public XPathExpression getExpr(String exp) { XPathExpression expr = expCache.get(exp); if (expr == null) { try { expr = xpath.compile(exp); if (expr != null) { expCache.put(exp, expr); } return expr; } catch (XPathExpressionException e) { LOG.error(e.getMessage(), e); return null; } } return expr; }
Example #10
Source File: XPathExpressionWrapper.java From XACML with MIT License | 6 votes |
public synchronized XPathExpression getXpathExpressionWrapped() { if (this.xpathExpressionWrapped == null && (this.getStatus() == null || this.getStatus().isOk())) { String thisPath = this.getPath(); if (thisPath != null) { XPath xPath = XPathFactory.newInstance().newXPath(); NamespaceContext namespaceContextThis = this.getNamespaceContext(); if (namespaceContextThis != null) { xPath.setNamespaceContext(namespaceContextThis); } try { this.xpathExpressionWrapped = xPath.compile(thisPath); } catch (XPathExpressionException ex) { this.status = new StdStatus(StdStatusCode.STATUS_CODE_SYNTAX_ERROR, "Error compiling XPath " + thisPath + ": " + ex.getMessage()); } } } return this.xpathExpressionWrapped; }
Example #11
Source File: OvmObject.java From cloudstack with Apache License 2.0 | 6 votes |
public List<String> xmlToList(String path, Document xmlDocument) throws Ovm3ResourceException { List<String> list = new ArrayList<String>(); XPathFactory factory = javax.xml.xpath.XPathFactory.newInstance(); XPath xPath = factory.newXPath(); try { XPathExpression xPathExpression = xPath.compile(path); NodeList nodeList = (NodeList) xPathExpression.evaluate(xmlDocument, XPathConstants.NODESET); for (int ind = 0; ind < nodeList.getLength(); ind++) { if (!nodeList.item(ind).getNodeValue().isEmpty()) { list.add("" + nodeList.item(ind).getNodeValue()); } else { list.add("" + nodeList.item(ind).getNodeValue()); } } return list; } catch (XPathExpressionException e) { throw new Ovm3ResourceException("Problem parsing XML to List: ", e); } }
Example #12
Source File: ParserHelper.java From JTAF-XCore with Apache License 2.0 | 6 votes |
public static final Element getOptionalElement(Element root, String xpath) throws MultipleMatchesException, NestedXPathException { try { XPathExpression expr = null; if ((expr = ParserHelper.compiledMap.get(xpath)) == null) { expr = getXPathFactory().newXPath().compile(xpath); ParserHelper.compiledMap.put(xpath, expr); } // I use a NodeList here instead of an Element because I want to ensure // there are not multiple return values NodeList nl = (NodeList) expr.evaluate(root, XPathConstants.NODESET); if (nl.getLength() > 1) { throw new MultipleMatchesException(xpath); } // TODO: Ensure the return value is an Element? return (Element) nl.item(0); } catch (XPathException e) { throw new NestedXPathException(e); } }
Example #13
Source File: TranslationStatistics.java From ToGoZip with GNU General Public License v3.0 | 5 votes |
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; }
Example #14
Source File: SubDocumentsParseFilter.java From storm-crawler with Apache License 2.0 | 5 votes |
@Override public void filter(String URL, byte[] content, DocumentFragment doc, ParseResult parse) { InputStream stream = new ByteArrayInputStream(content); try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); Document document = factory.newDocumentBuilder().parse(stream); Element root = document.getDocumentElement(); XPath xPath = XPathFactory.newInstance().newXPath(); XPathExpression expression = xPath.compile("//url"); NodeList nodes = (NodeList) expression.evaluate(root, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); expression = xPath.compile("loc"); Node child = (Node) expression.evaluate(node, XPathConstants.NODE); // create a subdocument for each url found in the sitemap ParseData parseData = parse.get(child.getTextContent()); NodeList childs = node.getChildNodes(); for (int j = 0; j < childs.getLength(); j++) { Node n = childs.item(j); parseData.put(n.getNodeName(), n.getTextContent()); } } } catch (Exception e) { LOG.error("Error processing sitemap from {}: {}", URL, e); } }
Example #15
Source File: P2Unzipper.java From packagedrone with Eclipse Public License 1.0 | 5 votes |
private void processMetaData ( final Context context, final InputStream in, final String filename, final String xpath ) throws Exception { // parse input final Document doc = this.xml.newDocumentBuilder ().parse ( new CloseShieldInputStream ( in ) ); final XPathExpression path = this.xml.newXPathFactory ().newXPath ().compile ( xpath ); // filter final NodeList result = XmlHelper.executePath ( doc, path ); // write filtered output final Document fragmentDoc = this.xml.newDocumentBuilder ().newDocument (); Node node = result.item ( 0 ); node = fragmentDoc.adoptNode ( node ); fragmentDoc.appendChild ( node ); // create artifact context.createVirtualArtifact ( filename, out -> { try { XmlHelper.write ( this.xml.newTransformerFactory (), fragmentDoc, new StreamResult ( out ) ); } catch ( final Exception e ) { throw new IOException ( e ); } }, null ); }
Example #16
Source File: ReferenceReplacer.java From android-string-extractor-plugin with MIT License | 5 votes |
private Element findElementByAndroidId(Document document, String id) throws XPathExpressionException { String expression = String.format("//*[@*[name()='android:id'] = '%s']", "@+id/" + id); XPathExpression expr = XPathFactory.newInstance().newXPath().compile(expression); return (Element) expr.evaluate(document, XPathConstants.NODE); }
Example #17
Source File: XMLEditor.java From MusicPlayer with MIT License | 5 votes |
public static void deletePlaylistFromXML(int selectedPlayListId) { try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(Resources.JAR + "library.xml"); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); // Finds the node with the play list id for removal. String query = "/library/playlists/playlist[@id='" + selectedPlayListId + "']"; XPathExpression expr = xpath.compile(query); Node deleteplaylistNode = (Node) expr.evaluate(doc, XPathConstants.NODE); // Removes the node corresponding to the selected song. deleteplaylistNode.getParentNode().removeChild(deleteplaylistNode); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(doc); File xmlFile = new File(Resources.JAR + "library.xml"); StreamResult result = new StreamResult(xmlFile); transformer.transform(source, result); } catch (Exception ex) { ex.printStackTrace(); } }
Example #18
Source File: XmlUtils.java From karate with MIT License | 5 votes |
private static XPathExpression compile(String path) { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); try { return xpath.compile(path); } catch (Exception e) { throw new RuntimeException(e); } }
Example #19
Source File: AbstractRequirementChecks.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
/** * DataObjectFormat/MimeType shall be present in B/T/LT/LTA */ public void checkDataObjectFormatMimeTypePresent() throws XPathExpressionException { XPathExpression exp = xpath.compile("//xades:SignedProperties/xades:SignedDataObjectProperties/xades:DataObjectFormat/xades:MimeType"); Node node = (Node) exp.evaluate(document, XPathConstants.NODE); assertNotNull(node); assertTrue(Utils.isStringNotEmpty(node.getTextContent())); }
Example #20
Source File: HeritrixConfigurationModifier.java From Asqatasun with GNU Affero General Public License v3.0 | 5 votes |
protected Node getNodeFromXpath (Document document) throws XPathExpressionException { if (this.xpathExpression == null) { this.xpathExpression = buildXpathExpression(); } XPathExpression xPathExpression = xpath.compile(this.xpathExpression); Object result = xPathExpression.evaluate(document, XPathConstants.NODESET); NodeList nodeList = (NodeList) result; if (nodeList.getLength() == 1) { return nodeList.item(0); } return null; }
Example #21
Source File: XQueryRunConfig.java From intellij-xquery with Apache License 2.0 | 5 votes |
private String getExpressionValue(XPathExpression expression) { try { return expression.evaluate(document); } catch (XPathExpressionException e) { throw new RuntimeException(e); } }
Example #22
Source File: ClangAnalyzerPlistParser.java From analysis-model with MIT License | 5 votes |
private static String extractField(final Element diag, final XPathExpression expr) throws XPathExpressionException { NodeList keys = (NodeList) expr.evaluate(diag, XPathConstants.NODESET); List<Element> elements = XmlElementUtil.nodeListToList(keys); if (elements.isEmpty()) { return ""; } return elements.get(0).getTextContent(); }
Example #23
Source File: DomHelper.java From mdw with Apache License 2.0 | 5 votes |
public static void poke(Document doc, String xpathExpr, String value) throws XPathExpressionException { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile(xpathExpr); NodeList nodeSet = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); if (nodeSet != null && nodeSet.getLength() > 0) { Node node = nodeSet.item(0); // first match if (node instanceof Attr) ((Attr) node).setValue(value); else node.getChildNodes().item(0).setNodeValue(value); } }
Example #24
Source File: ClangAnalyzerPlistParser.java From analysis-model with MIT License | 5 votes |
private static String getFileName(final List<String> files, final Element diag, final XPathExpression diagLocationFilePath) throws XPathExpressionException { int idx = extractIntField(diag, diagLocationFilePath); if (idx >= files.size()) { return "-"; } return files.get(idx); }
Example #25
Source File: XmlUtil.java From windup with Eclipse Public License 1.0 | 5 votes |
/** * Executes the given {@link XPathExpression} and returns the result with the type specified. */ public static Object executeXPath(Node document, XPathExpression expr, QName result) throws XPathException, MarshallingException { try { return expr.evaluate(document, result); } catch (Exception e) { throw new MarshallingException("Exception unmarshalling XML.", e); } }
Example #26
Source File: VariableReferenceExpression.java From microcks with Apache License 2.0 | 5 votes |
/** Extract a value from XML using a XPath expression. */ private static String getXPathValue(String xmlText, String xPathExp) { XPath xpath = XPathFactory.newInstance().newXPath(); try { XPathExpression expression = xpath.compile(xPathExp); return expression.evaluate(new InputSource(new StringReader(xmlText))); } catch (XPathExpressionException e) { log.warn("Exception while compiling/evaluating XPath", e); return null; } }
Example #27
Source File: XmlXPathRetrieve.java From butterfly with MIT License | 5 votes |
private XPathExpression checkXPathCompile(String expression) throws TransformationDefinitionException { XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); XPathExpression expr = null; try { expr = xpath.compile(expression); } catch (XPathExpressionException e) { throw new TransformationDefinitionException("XPath expression '" + expression + "' didn't compile correctly.", e); } return expr; }
Example #28
Source File: XmlExtractorTest.java From link-move with Apache License 2.0 | 5 votes |
@Before public void setUpXmlExtractor() throws IOException { inputStreamMock = mock(InputStream.class); streamConnectorMock = mock(StreamConnector.class); when(streamConnectorMock.getInputStream(anyMap())).thenReturn(inputStreamMock); xPathExpressionMock = mock(XPathExpression.class); xmlExtractor = new XmlExtractor(streamConnectorMock, new XmlRowAttribute[0], xPathExpressionMock); }
Example #29
Source File: AbstractRequirementChecks.java From dss with GNU Lesser General Public License v2.1 | 5 votes |
/** * DataObjectFormat with attribute ObjectReference shall be present in B/T/LT/LTA */ public void checkDataObjectFormatPresent() throws XPathExpressionException { XPathExpression exp = xpath.compile("//xades:SignedProperties/xades:SignedDataObjectProperties/xades:DataObjectFormat"); Node node = (Node) exp.evaluate(document, XPathConstants.NODE); assertNotNull(node); NamedNodeMap attributes = node.getAttributes(); Node objectReferenceAttribute = attributes.getNamedItem("ObjectReference"); assertTrue(Utils.isStringNotEmpty(objectReferenceAttribute.getTextContent())); }
Example #30
Source File: XPathEvaluationHelper.java From ph-schematron with Apache License 2.0 | 5 votes |
@Nullable public static String evaluateAsString (@Nonnull final XPathExpression aXPath, @Nonnull final Node aItem, @Nullable final String sBaseURI) throws XPathExpressionException { return evaluate (aXPath, aItem, XPathConstants.STRING, sBaseURI); }