//obtain Document somehow, doesn't matter how DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder(); org.w3c.dom.Document doc = b.parse(new FileInputStream("page.html")); //Evaluate XPath against Document itself XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList)xPath.evaluate("/html/body/p/div[3]/a", doc.getDocumentElement(), XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); ++i) { Element e = (Element) nodes.item(i); }
public static NodeList query(Node node, String searchString) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); return (NodeList) xpath.evaluate(searchString, node, XPathConstants.NODESET); }
import java.io.FileReader; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; public class GuestList { public static void main(String[] args) throws Exception { XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); NodeList shows = (NodeList) xPath.evaluate("/schedule/show", new InputSource(new FileReader( "tds.xml")), XPathConstants.NODESET); for (int i = 0; i < shows.getLength(); i++) { Element show = (Element) shows.item(i); String guestName = xPath.evaluate("guest/name", show); String guestCredit = xPath.evaluate("guest/credit", show); System.out.println(show.getAttribute("weekday") + ", " + show.getAttribute("date") + " - " + guestName + " (" + guestCredit + ")"); } } }
boolean exists = statusFile.exists(); if (exists) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); builder = dbf.newDocumentBuilder(); Document document = builder.parse(statusFile); NodeList indexNodeList = (NodeList) xPath.evaluate("/status/index", document, XPathConstants.NODESET); Element indexElement = (Element) indexNodeList.item(0); status.setLastIndexDate(format.parse(indexElement.getAttribute("dateProcessed"))); NodeList infos = (NodeList) xPath.evaluate("info", indexElement, XPathConstants.NODESET); for (int j = 0; j < infos.getLength(); j++) { Element info = (Element) infos.item(j); status.getAdditionalInfo().put(info.getAttribute("key"), info.getAttribute("val")); NodeList errorsNodeList = (NodeList) xPath.evaluate("/status/errors", document, XPathConstants.NODESET); if (errorsNodeList.getLength() > 0) { Element errorsElement = (Element) errorsNodeList.item(0); NodeList errors = (NodeList) xPath.evaluate("error", errorsElement, XPathConstants.NODESET); for (int j = 0; j < errors.getLength(); j++) { Element anError = (Element) errors.item(j); Long eventId = Long.valueOf(anError.getAttribute("key"));
@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; }
/** * Common routine to remove all children nodes from the passed element container * @param parentElement * @param nodeName * @throws XPathExpressionException */ protected void clearNode(Element parentElement, String nodeName) throws XPathExpressionException { if (parentElement.hasChildNodes()) { NodeList children = (NodeList) xPath.evaluate(nodeName, parentElement, XPathConstants.NODESET); for (int j = 0; j < children.getLength(); j++) { parentElement.removeChild(children.item(j)); } children = parentElement.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { if (children.item(j).getNodeName().equalsIgnoreCase("#text")) { parentElement.removeChild(children.item(j)); } } } }
private String xpath(String input, String expression) throws Exception { Node node = builderFactory.newDocumentBuilder().parse(new InputSource(new StringReader(input))); return (String) xpath.evaluate(expression, node, XPathConstants.STRING); } }
String xml = "<resp><status>good</status><msg>hi</msg></resp>"; InputSource source = new InputSource(new StringReader(xml)); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(source); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); String msg = xpath.evaluate("/resp/msg", document); String status = xpath.evaluate("/resp/status", document); System.out.println("msg=" + msg + ";" + "status=" + status);
try { final DocumentBuilder builder = XmlUtils.buildSecureDocumentBuilder(); final Document doc = builder.parse(conn.getInputStream()); final XPath xpath = XPathFactory.newInstance().newXPath(); final String numFound = xpath.evaluate("/response/result/@numFound", doc); if ("0".equals(numFound)) { missing = true; } else { result = new ArrayList<>(); final NodeList docs = (NodeList) xpath.evaluate("/response/result/doc", doc, XPathConstants.NODESET); for (int i = 0; i < docs.getLength(); i++) { final String g = xpath.evaluate("./str[@name='g']", docs.item(i)); LOGGER.trace("GroupId: {}", g); final String a = xpath.evaluate("./str[@name='a']", docs.item(i)); LOGGER.trace("ArtifactId: {}", a); final String v = xpath.evaluate("./str[@name='v']", docs.item(i)); final NodeList attributes = (NodeList) xpath.evaluate("./arr[@name='ec']/str", docs.item(i), XPathConstants.NODESET); boolean pomAvailable = false; boolean jarAvailable = false; for (int x = 0; x < attributes.getLength(); x++) { final String tmp = xpath.evaluate(".", attributes.item(x)); if (".pom".equals(tmp)) { pomAvailable = true;
while(resourceList.hasNext()) { ResourceInputStream myStream = resourceList.nextResource(); Document doc = builder.parse(myStream); NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET); int length = nodeList.getLength(); for (int j=0;j<length;j++) { Element element = (Element) nodeList.item(j); Resource resource = loader.getResource(element.getAttribute("resource")); ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(), resource.getURL().toString());
public static NodeList query(Node node, String searchString, XPathContext xpathcontext) throws XPathExpressionException { XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(xpathcontext); return (NodeList) xpath.evaluate(searchString, node, XPathConstants.NODESET); }
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class Demo { public static void main(String[] args) { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); Document dDoc = builder.parse("E:/test.xml"); XPath xPath = XPathFactory.newInstance().newXPath(); NodeList nl = (NodeList) xPath.evaluate("/root/author", dDoc, XPathConstants.NODESET); System.out.println(nl.getLength()); } catch (Exception e) { e.printStackTrace(); } } }
try { final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder(); final Document d = db.parse(stream); final XPath xpath = XPathFactory.newInstance().newXPath(); final List<NugetPackageReference> packages = new ArrayList<>(); final NodeList nodeList = (NodeList) xpath.evaluate("//PackageReference", d, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); final NamedNodeMap attrs = node.getAttributes();
NodeList deleteJobGroupNodes = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:pre-processing-commands/q:delete-jobs-in-group", document, XPathConstants.NODESET); NodeList deleteTriggerGroupNodes = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:pre-processing-commands/q:delete-triggers-in-group", document, XPathConstants.NODESET); NodeList deleteJobNodes = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:pre-processing-commands/q:delete-job", document, XPathConstants.NODESET); NodeList deleteTriggerNodes = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:pre-processing-commands/q:delete-trigger", document, XPathConstants.NODESET); NodeList jobNodes = (NodeList) xpath.evaluate("/q:job-scheduling-data/q:schedule/q:job", document, XPathConstants.NODESET); NodeList jobDataEntries = (NodeList) xpath.evaluate( "q:job-data-map/q:entry", jobDetailNode, XPathConstants.NODESET); NodeList triggerEntries = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:schedule/q:trigger/*", document, XPathConstants.NODESET); NodeList jobDataEntries = (NodeList) xpath.evaluate( "q:job-data-map/q:entry", triggerNode, XPathConstants.NODESET);
Element errorsElement = null; clearNode(rootElement, "errors"); NodeList indexNodeList = (NodeList) xPath.evaluate("/status/errors", document, XPathConstants.NODESET); if (indexNodeList.getLength() > 0) { errorsElement = (Element) indexNodeList.item(0); } else { if (status.getIndexErrors().size() > 0) { NodeList errors = (NodeList) xPath.evaluate("error[@key='" + entry.getKey() + "']", errorsElement, XPathConstants.NODESET); if (errors.getLength() == 0) { //add the error Element anError = document.createElement("error"); anError.setAttribute("key", entry.getKey().toString());
import java.io.StringReader; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.xml.sax.InputSource; public class Demo { public static void main(String[] args) throws Exception { String xml = "<car><manufacturer>toyota</manufacturer></car>"; String xpath = "/car/manufacturer"; XPath xPath = XPathFactory.newInstance().newXPath(); assertEquals("toyota",xPath.evaluate(xpath, new InputSource(new StringReader(xml)))); } }
import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.NodeList; public class Demo { public static void main(String[] args) { DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder builder = domFactory.newDocumentBuilder(); Document dDoc = builder.parse("E:/test.xml"); XPath xPath = XPathFactory.newInstance().newXPath(); Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE); System.out.println(node.getNodeValue()); } catch (Exception e) { e.printStackTrace(); } } }
try { final DocumentBuilder db = XmlUtils.buildSecureDocumentBuilder(); final Document d = db.parse(stream); final XPath xpath = XPathFactory.newInstance().newXPath(); final List<NugetPackageReference> packages = new ArrayList<>(); final NodeList nodeList = (NodeList) xpath.evaluate("/packages/package", d, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { final Node node = nodeList.item(i); final NamedNodeMap attrs = node.getAttributes(); final Node id = attrs.getNamedItem("id");
NodeList deleteJobGroupNodes = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:pre-processing-commands/q:delete-jobs-in-group", document, XPathConstants.NODESET); NodeList deleteTriggerGroupNodes = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:pre-processing-commands/q:delete-triggers-in-group", document, XPathConstants.NODESET); NodeList deleteJobNodes = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:pre-processing-commands/q:delete-job", document, XPathConstants.NODESET); NodeList deleteTriggerNodes = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:pre-processing-commands/q:delete-trigger", document, XPathConstants.NODESET); NodeList jobNodes = (NodeList) xpath.evaluate("/q:job-scheduling-data/q:schedule/q:job", document, XPathConstants.NODESET); NodeList jobDataEntries = (NodeList) xpath.evaluate( "q:job-data-map/q:entry", jobDetailNode, XPathConstants.NODESET); NodeList triggerEntries = (NodeList) xpath.evaluate( "/q:job-scheduling-data/q:schedule/q:trigger/*", document, XPathConstants.NODESET); NodeList jobDataEntries = (NodeList) xpath.evaluate( "q:job-data-map/q:entry", triggerNode, XPathConstants.NODESET);