/** * 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); }
public static void processXmlFile(String xmlFullFilename, List<RDotTxtEntry> references, AaptResourceCollector resourceCollector) throws IOException, XPathExpressionException { Document document = JavaXmlUtil.parse(xmlFullFilename); NodeList nodesWithIds = (NodeList) ANDROID_ID_DEFINITION.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodesWithIds.getLength(); i++) { String resourceName = nodesWithIds.item(i).getNodeValue(); if (!resourceName.startsWith(ID_DEFINITION_PREFIX)) { throw new AaptUtilException("Invalid definition of a resource: '" + resourceName + "'"); NodeList nodesUsingIds = (NodeList) ANDROID_ID_USAGE.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodesUsingIds.getLength(); i++) { String resourceName = nodesUsingIds.item(i).getNodeValue(); int slashPosition = resourceName.indexOf('/'); if (slashPosition < 0) {
public InputStream sanitize(InputStream in) throws Exception { byte [] content = IOUtils.toByteArray(in); try { // storing the entire file in memory in case we need to bail. Document doc = builder.parse(new ByteArrayInputStream(content)); doc.setXmlStandalone(true); Object result = expression.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { nodes.item(i).setTextContent(""); } DOMSource source = new DOMSource(doc); ByteArrayOutputStream output = new ByteArrayOutputStream(); StreamResult outStream = new StreamResult(output); transformer.transform(source, outStream); return new ByteArrayInputStream(output.toByteArray()); } catch (Exception e) { ROOT_LOGGER.debug("Error while sanitizing an xml document", e); return new ByteArrayInputStream(content); } } }
expression = xpath.compile(path); } catch (XPathExpressionException e) { expression = null; try { initializeDocumentBuilderFactory(); builder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new RuntimeException("Error instantiating DocumentBuilder, cannot build xml parser", e); return expression.evaluate(builder.parse(inputSource), qname); } catch (XPathExpressionException e) { throw new RuntimeException ("Invalid expression '" + oldPath + "'", e);
/** * 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; }
/** * 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; }
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()); }
DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(data); Object result = xpathExpr.evaluate(doc, XPathConstants.NODESET); nodes = (NodeList) result; } catch (XPathExpressionException e) { for (int i = 0; i < nodes.getLength(); ++i) { Node node = nodes.item(i); if (!(node instanceof Element)) { continue;
Object result; try { result = xPathExpression.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { result = xPathExpression.evaluate(document, XPathConstants.STRING); if (nodeList.getLength() == 0) { return null; Node item = nodeList.item(0); if (item.getNodeType() == Node.ATTRIBUTE_NODE || item.getNodeType() == Node.TEXT_NODE) { return item.getTextContent();
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; }
String versioNummer = expr.evaluate(doc); RoleXMLXpath xmlXPath = XMLXpathFactory.Singleton.getRoleXMLXpath(versioNummer); xmlXPath.getRoleListExpression().evaluate(doc, XPathConstants.NODESET); String roleName = xmlXPath.getRoleNameExpression().evaluate(roleNode); NodeList propertyNodes = (NodeList) xmlXPath.getRolePropertiesExpression() .evaluate(roleNode, XPathConstants.NODESET); Properties roleProps = new Properties(); for (int j = 0; j < propertyNodes.getLength(); j++) { Node propertyNode = propertyNodes.item(j); String propertyName = xmlXPath.getPropertyNameExpression().evaluate(propertyNode); String propertyValue = xmlXPath.getPropertyValueExpression().evaluate(propertyNode); roleProps.put(propertyName, propertyValue); for (int i = 0; i < roleNodes.getLength(); i++) { Node roleNode = roleNodes.item(i); String roleName = xmlXPath.getRoleNameExpression().evaluate(roleNode); String parentName = xmlXPath.getParentExpression().evaluate(roleNode); if (parentName != null && parentName.length() > 0) { helper.role_parentMap.put( xmlXPath.getUserRolesExpression().evaluate(doc, XPathConstants.NODESET); String userName = xmlXPath.getUserNameExpression().evaluate(userRolesNode);
Object result; try { result = xPathExpression.evaluate(document, XPathConstants.NODESET); } catch (XPathExpressionException e) { result = xPathExpression.evaluate(document, XPathConstants.STRING); StreamResult xmlOutput = new StreamResult(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); for (int i = 0; i < nodeList.getLength(); i++) { Node item = nodeList.item(i); if (item.getNodeType() == Node.ATTRIBUTE_NODE || item.getNodeType() == Node.TEXT_NODE) { results.add(item.getTextContent());
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);
String versionNummer = expr.evaluate(doc); UserGroupXMLXpath xmlXPath = XMLXpathFactory.Singleton.getUserGroupXMLXpath(versionNummer); xmlXPath.getUserListExpression().evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < userNodes.getLength(); i++) { Node userNode = userNodes.item(i); boolean userEnabled = Util.convertToBoolean( xmlXPath.getUserEnabledExpression().evaluate(userNode), true); String userPassword = null; userPassword = xmlXPath.getUserPasswordExpression().evaluate(userNode); String userName = xmlXPath.getUserNameExpression().evaluate(userNode); NodeList propertyNodes = (NodeList) xmlXPath.getUserPropertiesExpression() .evaluate(userNode, XPathConstants.NODESET); Properties userProps = new Properties(); for (int j = 0; j < propertyNodes.getLength(); j++) { Node propertyNode = propertyNodes.item(j); String propertyName = xmlXPath.getPropertyNameExpression().evaluate(propertyNode); String propertyValue = xmlXPath.getPropertyValueExpression().evaluate(propertyNode); userProps.put(propertyName, propertyValue); xmlXPath.getGroupListExpression().evaluate(doc, XPathConstants.NODESET);
public static void processXmlFile(String xmlFullFilename, List<RDotTxtEntry> references, AaptResourceCollector resourceCollector) throws IOException, XPathExpressionException { Document document = JavaXmlUtil.parse(xmlFullFilename); NodeList nodesWithIds = (NodeList) ANDROID_ID_DEFINITION.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodesWithIds.getLength(); i++) { String resourceName = nodesWithIds.item(i).getNodeValue(); if (!resourceName.startsWith(ID_DEFINITION_PREFIX)) { throw new AaptUtilException("Invalid definition of a resource: '" + resourceName + "'"); NodeList nodesUsingIds = (NodeList) ANDROID_ID_USAGE.evaluate(document, XPathConstants.NODESET); for (int i = 0; i < nodesUsingIds.getLength(); i++) { String resourceName = nodesUsingIds.item(i).getNodeValue(); int slashPosition = resourceName.indexOf('/'); if (slashPosition < 0) {
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); }
@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; }
String xml = expr.evaluate(doc); if (!xml.equals("")) { NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET); if (nodes.getLength() > 1) { log.debug("One of our NED tiles requires more than one tile from the server. This is slightly inefficient, and sort of yucky."); for (int i = 0; i < nodes.getLength(); ++i) { Node node = nodes.item(i); String urlString = node.getTextContent().trim(); log.info("Getting URL {}/{}", ++nd, payloads.size());
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);