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 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()); }
List<T> out = new ArrayList<T>(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // never forget this! 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; Node child = node.getFirstChild(); NamedNodeMap attrs = node.getAttributes(); int lastAttr = attrs.getLength() - 1; for (int j = lastAttr; j--> 0; ) { child = child.getNextSibling(); continue;
Document doc = docBuilder.parse(is); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); NodeList textnl = (NodeList) TEXT_NODES_EXAMPLE.evaluate(doc, XPathConstants.NODESET); if (textnl.getLength() == 0) { textnl = (NodeList) TEXT_NODES_SAMPLE.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < textnl.getLength(); i++) { Node textnode = textnl.item(i); current_text = attrib(textnode, "xml:id", true); NodeList divnl = (NodeList) DIV_NODES.evaluate(textnode, XPathConstants.NODESET); for (int j = 0; j < divnl.getLength(); j++) { Node divnode = divnl.item(j); NodeList paranl = (NodeList) PARA_NODES.evaluate(divnode, XPathConstants.NODESET); for (int k = 0; k < paranl.getLength(); k++) { String pid = attrib(pnode, "xml:id", true); if (pnode.getChildNodes().getLength() != 1 && !pnode.getFirstChild().getNodeName().equals("#text")) { throw new IOException("Unexpected content in p element " + pid);
String to = assignment.getTo(); XPathFactory factory = XPathFactory.newInstance(); XPath xpathFrom = factory.newXPath(); XPathExpression exprFrom = xpathFrom.compile(from); XPath xpathTo = factory.newXPath(); XPathExpression exprTo = xpathTo.compile(to); parent = ((org.w3c.dom.Node) target).getParentNode(); targetElem = exprTo.evaluate(parent, XPathConstants.NODE); nl = (NodeList) exprFrom.evaluate(source, XPathConstants.NODESET); } else if (source instanceof String) { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.newDocument(); if (nl.getLength() == 0) { throw new RuntimeException("Nothing was selected by the from expression " + from + " on " + sourceExpr); for (int i = 0 ; i < nl.getLength(); i++) {
/** * 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); }
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setXIncludeAware(true); factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); final Document document = factory.newDocumentBuilder().parse(in); final XPath xPath = XPathFactory.newInstance().newXPath(); errorHandler.checkIfShouldExit(); final Node schemaNode = (Node)xPath.compile(MESSAGE_SCHEMA_XPATH_EXPR).evaluate(document, XPathConstants.NODE); final MessageSchema messageSchema = new MessageSchema(schemaNode, typeByNameMap, messageByIdMap); errorHandler.checkIfShouldExit();
XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xpath = xPathFactory.newXPath(); XPathExpression compiledExpression = xpath .compile(expression); return merge(compiledExpression, files); File... files) throws Exception { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory .newInstance(); docBuilderFactory .setIgnoringElementContentWhitespace(true); DocumentBuilder docBuilder = docBuilderFactory .newDocumentBuilder(); Document base = docBuilder.parse(files[0]); Node results = (Node) expression.evaluate(base, XPathConstants.NODE); if (results == null) { Document merge = docBuilder.parse(files[i]); Node nextResults = (Node) expression.evaluate(merge, XPathConstants.NODE); while (nextResults.hasChildNodes()) { Node kid = nextResults.getFirstChild(); nextResults.removeChild(kid); kid = base.importNode(kid, true); results.appendChild(kid);
public <E> Map<String, E> xmlToMap(String path, Document xmlDocument) throws Ovm3ResourceException { 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); Map<String, E> myMap = new HashMap<String, E>(); for (int ind = 0; ind < nodeList.getLength(); ind++) { NodeList nodeListFor = nodeList.item(ind).getChildNodes(); for (int index = 0; index < nodeListFor.getLength(); index++) { String rnode = nodeListFor.item(index).getNodeName(); NodeList nodeListFor2 = nodeListFor.item(index).getChildNodes(); if (nodeListFor2.getLength() > 1) { /* Do we need to figure out all the sub elements here and put them in a map? */ } else { String element = nodeListFor.item(index).getNodeValue(); myMap.put(rnode, (E) element); } } } return myMap; } catch (XPathExpressionException e) { throw new Ovm3ResourceException("Problem parsing XML to Map:", e); } }
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(); } else { StreamResult xmlOutput = new StreamResult(new StringWriter());
import java.io.File; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.*; import org.w3c.dom.*; public class Demo { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document document = dbf.newDocumentBuilder().parse(new File("input.xml")); XPathFactory xpf = XPathFactory.newInstance(); XPath xpath = xpf.newXPath(); XPathExpression expression = xpath.compile("//A/B[C/E/text()=13]"); Node b13Node = (Node) expression.evaluate(document, XPathConstants.NODE); b13Node.getParentNode().removeChild(b13Node); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(document), new StreamResult(System.out)); } }
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); } } }
@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; }
public boolean responseNotEmpty(String response) throws ExecutionException { NodeList response_body; Document doc = getDocument(response); XPath xpath = XPathFactory.newInstance().newXPath(); try { XPathExpression expr = xpath.compile("/response[@status='success']"); response_body = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); } catch (XPathExpressionException e) { throw new ExecutionException(e.getCause().getMessage()); } if (response_body.getLength() > 0 && (!response_body.item(0).getTextContent().equals("") || (response_body.item(0).hasChildNodes() && response_body.item(0).getFirstChild().hasChildNodes()))) { return true; } else { return false; } }
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);
@Override protected final Optional<String[]> doExtract(final HttpRequest request) { try { Optional<InputSource> source = helper.extractAsInputSource(request, extractor); if (!source.isPresent()) { return absent(); } NodeList list = (NodeList) xPathExpression.evaluate(source.get(), XPathConstants.NODESET); if (list.getLength() == 0) { return absent(); } return doExtract(list); } catch (XPathExpressionException e) { return absent(); } }
XPathExpression expr = xpath.compile("/howto/topic[@name='PowerBuilder']/url"); NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
/** * 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; }