/** * 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); }
private static XPathExpression compileXpathExpression(String expression, @Nullable Map<String, String> namespaces) throws XPathExpressionException { SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext(); namespaceContext.setBindings(namespaces != null ? namespaces : Collections.emptyMap()); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(namespaceContext); return xpath.compile(expression); }
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);
/** * Checks in under a given root element whether it can find a child elements * which match the XPath expression supplied. Returns a {@link List} of * {@link Element} if they exist. Please note that the XPath parser used is * NOT namespace aware. So if you want to find a element <beans><sec:http> * you need to use the following XPath expression '/beans/http'. * * @param xPathExpression the xPathExpression * @param root the parent DOM element * @return a {@link List} of type {@link Element} if discovered, otherwise * an empty list (never null) */ public static List<Element> findElements(final String xPathExpression, final Element root) { final List<Element> elements = new ArrayList<Element>(); NodeList nodes = null; try { XPathExpression expr = COMPILED_EXPRESSION_CACHE.get(xPathExpression); if (expr == null) { expr = XPATH.compile(xPathExpression); COMPILED_EXPRESSION_CACHE.put(xPathExpression, expr); } nodes = (NodeList) expr.evaluate(root, XPathConstants.NODESET); } catch (final XPathExpressionException e) { throw new IllegalArgumentException("Unable evaluate xpath expression", e); } for (int i = 0, n = nodes.getLength(); i < n; i++) { elements.add((Element) nodes.item(i)); } return elements; }
public Object eval(String xml, String path, QName qname) { if (xml == null || path == null || qname == null) { return null; } if (xml.length() == 0 || path.length() == 0) { return null; } if (!path.equals(oldPath)) { try { expression = xpath.compile(path); } catch (XPathExpressionException e) { expression = null; } oldPath = path; } if (expression == null) { return null; } reader.set(xml); try { return expression.evaluate(inputSource, qname); } catch (XPathExpressionException e) { throw new RuntimeException ("Invalid expression '" + oldPath + "'", e); } }
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(); }
String url = "http://stackoverflow.com/questions/3152138"; Document document = new Tidy().parseDOM(new URL(url).openStream(), null); XPath xpath = XPathFactory.newInstance().newXPath(); Node question = (Node) xpath.compile("//*[@id='question']//*[contains(@class,'post-text')]//p[1]").evaluate(document, XPathConstants.NODE); System.out.println("Question: " + question.getFirstChild().getNodeValue()); NodeList answerers = (NodeList) xpath.compile("//*[@id='answers']//*[contains(@class,'user-details')]//a[1]").evaluate(document, XPathConstants.NODESET); for (int i = 0; i < answerers.getLength(); i++) { System.out.println("Answerer: " + answerers.item(i).getFirstChild().getNodeValue()); }
private static XPathExpression createExpression(String expressionStr) { try { return XPathFactory.newInstance().newXPath().compile(expressionStr); } catch (XPathExpressionException e) { throw new AaptUtilException(e); } }
/** * Scan XML for all message definitions and save in map * * @param document for the XML parsing * @param xPath for XPath expression reuse * @param typeByNameMap to use for Type objects * @return {@link java.util.Map} of schemaId to Message * @throws Exception on parsing error. */ public static Map<Long, Message> findMessages( final Document document, final XPath xPath, final Map<String, Type> typeByNameMap) throws Exception { final Map<Long, Message> messageByIdMap = new HashMap<>(); final ObjectHashSet<String> distinctNames = new ObjectHashSet<>(); forEach((NodeList)xPath.compile(MESSAGE_XPATH_EXPR).evaluate(document, XPathConstants.NODESET), (node) -> addMessageWithIdCheck(distinctNames, messageByIdMap, new Message(node, typeByNameMap), node)); return messageByIdMap; }
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse("<Your xml doc uri>"); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression expr = xpath.compile("//Type[@type_id=\"4218\"]"); NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
public static boolean nodeExists(InputSource inputSource, String xpath) throws XPathExpressionException { XPathFactory factory = XPathFactory.newInstance(); XPathExpression expression = factory.newXPath().compile(xpath); Boolean b = (Boolean) expression.evaluate(inputSource, XPathConstants.BOOLEAN); return b != null && b; }
private static XPathExpression compiledXPath(String xPathExpression, NamespaceContext namespaceContext) { try { final XPath xPath = XPathFactory.newInstance().newXPath(); if (namespaceContext != null) { xPath.setNamespaceContext(namespaceContext); } return xPath.compile(xPathExpression); } catch (XPathExpressionException e) { throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e); } }
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse("persons.xml"); XPath xpath = XPathFactory.newInstance().newXPath(); // XPath Query for showing all nodes value XPathExpression expr = xpath.compile("//person/*/text()"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { System.out.println(nodes.item(i).getNodeValue()); } }
XPathFactory xpathFactory = XPathFactory.newInstance(); // XPath to find empty text nodes. XPathExpression xpathExp = xpathFactory.newXPath().compile( "//text()[normalize-space(.) = '']"); NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyTextNodes.getLength(); i++) { Node emptyTextNode = emptyTextNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); }
public XPathRequestExtractor(final String xpath) { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath target = xPathfactory.newXPath(); try { xPathExpression = target.compile(xpath); } catch (XPathExpressionException e) { throw new IllegalArgumentException(e); } }
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); } }
private static long latestTimestamp(Document document) { XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); xpath.setNamespaceContext(TtmlHelpers.NAMESPACE_CONTEXT); try { XPathExpression xp = xpath.compile("//*[name()='p']"); NodeList timedNodes = (NodeList) xp.evaluate(document, XPathConstants.NODESET); long lastTimeStamp = 0; for (int i = 0; i < timedNodes.getLength(); i++) { lastTimeStamp = Math.max(getEndTime(timedNodes.item(i)), lastTimeStamp); } return lastTimeStamp; } catch (XPathExpressionException e) { throw new RuntimeException(e); } }
public void setPath(String path) { this.path = path; XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); try { xpathExpr = xpath.compile(path); } catch (XPathExpressionException e) { throw new RuntimeException(e); } }
"\r\n" + // "</urn:ResponseStatus>"; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new java.io.ByteArrayInputStream(xml.getBytes())); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new NamespaceContext() { public String getNamespaceURI(String prefix) { XPathExpression expr = xpath.compile("//urn:ResponseStatus"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { Node currentItem = nodes.item(i); System.out.println("found node -> " + currentItem.getLocalName() + " (namespace: " + currentItem.getNamespaceURI() + ")");