List of usage examples for javax.xml.xpath XPathExpression evaluate
public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File("Table.xml")); XPathFactory xFactory = XPathFactory.newInstance(); XPath path = xFactory.newXPath(); XPathExpression exp = path.compile("/tables/table"); NodeList nlTables = (NodeList) exp.evaluate(doc, XPathConstants.NODESET); for (int tblIndex = 0; tblIndex < nlTables.getLength(); tblIndex++) { Node table = nlTables.item(tblIndex); Node nAtt = table.getAttributes().getNamedItem("title"); System.out.println(nAtt.getTextContent()); exp = path.compile("headings/heading"); NodeList nlHeaders = (NodeList) exp.evaluate(table, XPathConstants.NODESET); Set<String> headers = new HashSet<String>(25); for (int index = 0; index < nlHeaders.getLength(); index++) { headers.add(nlHeaders.item(index).getTextContent().trim()); }/*from www . j av a 2 s . co m*/ for (String header : headers) { System.out.println(header); } exp = path.compile("tablebody/tablerow"); NodeList nlRows = (NodeList) exp.evaluate(table, XPathConstants.NODESET); for (int index = 0; index < nlRows.getLength(); index++) { Node rowNode = nlRows.item(index); exp = path.compile("tablecell/item"); NodeList nlValues = (NodeList) exp.evaluate(rowNode, XPathConstants.NODESET); List<String> values = new ArrayList<String>(25); for (int valueIndex = 0; valueIndex < nlValues.getLength(); valueIndex++) { values.add(nlValues.item(valueIndex).getTextContent().trim()); } for (String value : values) { System.out.println(value); } } } }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File("path/to/file.xml")); XPathFactory xFactory = XPathFactory.newInstance(); XPath xPath = xFactory.newXPath(); XPathExpression expression = xPath.compile("PersonList/Person/Age/text() | PersonList/Person/Name/text()"); NodeList nodes = (NodeList) expression.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getParentNode().getNodeName().equals("Name")) { node.setNodeValue("new name"); } else {/* w w w .j a v a 2s . c om*/ node.setNodeValue("42"); } } }
From source file:Main.java
License:asdf
public static void main(String[] args) throws Exception { String xml = "<soapenv:Envelope " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " + "xmlns:ser=\"http://services.web.post.list.com\"><soapenv:Header>" + "<authInfo xsi:type=\"soap:authentication\" " + "xmlns:soap=\"http://list.com/services/SoapRequestProcessor\">" + "<username xsi:type=\"xsd:string\">asdf@g.com</username>" + "<password xsi:type=\"xsd:string\">asdf</password></authInfo></soapenv:Header></soapenv:Envelope>"; System.out.println(xml);// w w w.j a va 2 s .co m DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); DocumentBuilder builder = domFactory.newDocumentBuilder(); Document doc = builder.parse(new InputSource(new StringReader(xml))); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(new NamespaceContext() { @Override public Iterator getPrefixes(String arg0) { return null; } @Override public String getPrefix(String arg0) { return null; } @Override public String getNamespaceURI(String arg0) { if ("soapenv".equals(arg0)) { return "http://schemas.xmlsoap.org/soap/envelope/"; } return null; } }); XPathExpression expr = xpath.compile("/soapenv:Envelope/soapenv:Header/authInfo/password"); Object result = expr.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; System.out.println("Got " + nodes.getLength() + " nodes"); }
From source file:Main.java
public static void main(String[] args) throws Exception { Main example = new Main(); example.data.put("France", "Paris"); example.data.put("Japan", "Tokyo"); JAXBContext context = JAXBContext.newInstance(Main.class); Marshaller marshaller = context.createMarshaller(); DOMResult result = new DOMResult(); marshaller.marshal(example, result); XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Document document = (Document) result.getNode(); XPathExpression expression = xpath.compile("//map/entry"); NodeList nodes = (NodeList) expression.evaluate(document, XPathConstants.NODESET); expression = xpath.compile("//map"); Node oldMap = (Node) expression.evaluate(document, XPathConstants.NODE); Element newMap = document.createElement("map"); for (int index = 0; index < nodes.getLength(); index++) { Element element = (Element) nodes.item(index); newMap.setAttribute(element.getAttribute("key"), element.getAttribute("value")); }//from ww w . j a v a2 s. c om expression = xpath.compile("//map/.."); Node parent = (Node) expression.evaluate(document, XPathConstants.NODE); parent.replaceChild(newMap, oldMap); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(System.out)); }
From source file:Main.java
public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document doc = factory.newDocumentBuilder().parse(new File("Sample.xml")); XPathFactory xFactory = XPathFactory.newInstance(); XPath xPath = xFactory.newXPath(); XPathExpression exp = xPath.compile( "/article/body/section/region[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), 'perfect')]"); NodeList nl = (NodeList) exp.evaluate(doc.getFirstChild(), XPathConstants.NODESET); for (int index = 0; index < nl.getLength(); index++) { Node node = nl.item(index); System.out.println(node.getTextContent()); }//from w w w . j ava 2 s.co m }
From source file:Main.java
public static void main(String[] args) throws Exception { XPathFactory xpf = XPathFactory.newInstance(); XPath xp = xpf.newXPath();/* w ww. j av a2 s .co m*/ xp.setNamespaceContext(new MyNamespaceContext()); XPathExpression xpe = xp.compile("ns:feed/ns:entry"); FileInputStream xmlStream = new FileInputStream("input.xml"); InputSource xmlInput = new InputSource(xmlStream); Element result = (Element) xpe.evaluate(xmlInput, XPathConstants.NODE); System.out.println(result); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { SimpleDateFormat xmlDateFormat = new SimpleDateFormat("MM.dd.yy"); MapVariableResolver resolver = new MapVariableResolver(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document document = builder.parse(new File("t.xml")); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); xPath.setXPathVariableResolver(resolver); XPathExpression expression = xPath.compile("/schedule/show[@date=$date]/guest"); String formattedDate = xmlDateFormat.format(new Date(2006, 5, 14)); resolver.addVariable(null, "date", formattedDate); Element guest = (Element) expression.evaluate(document, XPathConstants.NODE); System.out.println(guest.getElementsByTagName("name").item(0).getTextContent()); }
From source file:ApplyXPathJAXP.java
public static void main(String[] args) { QName returnType = null;//from ww w . jav a 2 s . co m if (args.length != 3) { System.err.println("Usage: java ApplyXPathAPI xml_file xpath_expression type"); } InputSource xml = new InputSource(args[0]); String expr = args[1]; // set the return type if (args[2].equals("num")) returnType = XPathConstants.NUMBER; else if (args[2].equals("bool")) returnType = XPathConstants.BOOLEAN; else if (args[2].equals("str")) returnType = XPathConstants.STRING; else if (args[2].equals("node")) returnType = XPathConstants.NODE; else if (args[2].equals("nodeset")) returnType = XPathConstants.NODESET; else System.err.println("Invalid return type: " + args[2]); // Create a new XPath XPathFactory factory = XPathFactory.newInstance(); XPath xpath = factory.newXPath(); Object result = null; try { // compile the XPath expression XPathExpression xpathExpr = xpath.compile(expr); // Evaluate the XPath expression against the input document result = xpathExpr.evaluate(xml, returnType); // Print the result to System.out. printResult(result); } catch (Exception e) { e.printStackTrace(); } }
From source file:Main.java
public static void main(String[] args) throws Exception { XPathFactory xpf = XPathFactory.newInstance(); XPath xPath = xpf.newXPath(); XPathExpression schoolNameExpression = xPath.compile("SchoolName"); XPathExpression classNameExpression = xPath.compile("Classes/Class/ClassName"); InputSource inputSource = new InputSource("input.xml"); NodeList schoolNodes = (NodeList) xPath.evaluate("/Data/Schools/School", inputSource, XPathConstants.NODESET); for (int x = 0; x < schoolNodes.getLength(); x++) { Node schoolElement = schoolNodes.item(x); System.out.println(schoolNameExpression.evaluate(schoolElement, XPathConstants.STRING)); NodeList classNames = (NodeList) classNameExpression.evaluate(schoolElement, XPathConstants.NODESET); for (int y = 0; y < classNames.getLength(); y++) { System.out.println(classNames.item(y).getTextContent()); }/*from ww w . j av a 2 s . c om*/ } }
From source file:AwsConsoleApp.java
public static void main(String[] args) throws Exception { System.out.println("==========================================="); System.out.println("Welcome to the AWS VPN connection creator"); System.out.println("==========================================="); init();//from w w w . j a v a2s . com List<String> CIDRblocks = new ArrayList<String>(); String vpnType = null; String vpnGatewayId = null; String customerGatewayId = null; String customerGatewayInfoPath = null; String routes = null; options.addOption("h", "help", false, "show help."); options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)"); options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)"); options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)"); options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24"); options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml"); CommandLineParser parser = new BasicParser(); CommandLine cmd = null; // Parse command line options try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) help(); if (cmd.hasOption("vt")) { log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt")); vpnType = cmd.getOptionValue("vt"); // Whatever you want to do with the setting goes here } else { log.log(Level.SEVERE, "Missing vt option"); help(); } if (cmd.hasOption("vgw")) { log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw")); vpnGatewayId = cmd.getOptionValue("vgw"); } else { log.log(Level.SEVERE, "Missing vgw option"); help(); } if (cmd.hasOption("cgw")) { log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw")); customerGatewayId = cmd.getOptionValue("cgw"); } else { log.log(Level.SEVERE, "Missing cgw option"); help(); } if (cmd.hasOption("r")) { log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r")); routes = cmd.getOptionValue("r"); String[] routeItems = routes.split(","); CIDRblocks = Arrays.asList(routeItems); } else { log.log(Level.SEVERE, "Missing r option"); help(); } if (cmd.hasOption("vi")) { log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi")); customerGatewayInfoPath = cmd.getOptionValue("vi"); } else { log.log(Level.SEVERE, "Missing vi option"); help(); } } catch (ParseException e) { log.log(Level.SEVERE, "Failed to parse comand line properties", e); help(); } /* * Amazon VPC * Create and delete VPN tunnel to customer VPN hardware */ try { //String vpnType = "ipsec.1"; //String vpnGatewayId = "vgw-eca54d85"; //String customerGatewayId = "cgw-c16e87a8"; //List<String> CIDRblocks = new ArrayList<String>(); //CIDRblocks.add("10.77.77.0/24"); //CIDRblocks.add("172.16.1.0/24"); //CIDRblocks.add("172.18.1.0/24"); //CIDRblocks.add("10.66.66.0/24"); //CIDRblocks.add("10.8.1.0/24"); //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml"; Boolean staticRoutesOnly = true; List<String> connectionIds = new ArrayList<String>(); List<String> connectionIdList = new ArrayList<String>(); connectionIdList = vpnExists(connectionIds); if (connectionIdList.size() == 0) { CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId, vpnGatewayId); CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult(); VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification(); vpnspec.setStaticRoutesOnly(staticRoutesOnly); vpnReq.setOptions(vpnspec); System.out.println("Creating VPN connection"); vpnRes = ec2.createVpnConnection(vpnReq); String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId(); String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration(); //System.out.println("Customer Gateway Info:" + customerGatewayInfo); // Write Customer Gateway Info to file System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath); try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) { out.print(customerGatewayInfo); } System.out.println("Creating VPN routes"); for (String destCIDR : CIDRblocks) { CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest(); CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult(); routeReq.setDestinationCidrBlock(destCIDR); routeReq.setVpnConnectionId(vpnConnId); routeRes = ec2.createVpnConnectionRoute(routeReq); } // Parse XML file File file = new File(customerGatewayInfoPath); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse(customerGatewayInfoPath); XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); XPathExpression exprGetipAddress = xpath .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address"); NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET); if (vpnGateway != null) { for (int i = 0; i < vpnGateway.getLength(); i++) { String vpnGatewayIP = vpnGateway.item(i).getTextContent(); System.out .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP); } } System.out.println("=============================================="); XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key"); NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET); if (presharedKeyList != null) { for (int i = 0; i < presharedKeyList.getLength(); i++) { String pre_shared_key = presharedKeyList.item(i).getTextContent(); System.out.println( "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key); } } System.out.println("Creating VPN creation completed!"); } else { boolean yn; Scanner scan = new Scanner(System.in); System.out.println("Enter yes or no to delete VPN connection: "); String input = scan.next(); String answer = input.trim().toLowerCase(); while (true) { if (answer.equals("yes")) { yn = true; break; } else if (answer.equals("no")) { yn = false; System.exit(0); } else { System.out.println("Sorry, I didn't catch that. Please answer yes/no"); } } // Delete all existing VPN connections System.out.println("Deleting AWS VPN connection(s)"); for (String vpnConID : connectionIdList) { DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult(); DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest(); delVPNreq.setVpnConnectionId(vpnConID); delVPNres = ec2.deleteVpnConnection(delVPNreq); System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID); } } } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); } }