Example usage for javax.xml.xpath XPath compile

List of usage examples for javax.xml.xpath XPath compile

Introduction

In this page you can find the example usage for javax.xml.xpath XPath compile.

Prototype

public XPathExpression compile(String expression) throws XPathExpressionException;

Source Link

Document

Compile an XPath expression for later evaluation.

Usage

From source file:Main.java

public static void main(String[] args) throws Throwable {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    String entryType = null;/*from   w  w w.  ja v  a2  s .c  o  m*/
    XPathExpression[] expressions = new XPathExpression[] {
            xpath.compile("local-name(*[local-name() = 'package'])"),
            xpath.compile("local-name(*[local-name() = 'libapp'])"),
            xpath.compile("local-name(*[local-name() = 'module'])") };

    DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = fac.newDocumentBuilder();
    Document doc = parser.parse(args[0]);

    for (int i = 0; i < expressions.length; i++) {
        String found = (String) expressions[i].evaluate(doc.getDocumentElement(), XPathConstants.STRING);
        entryType = mappings.get(found);
        if (entryType != null && !entryType.trim().isEmpty()) {
            break;
        }
    }
    System.out.println(entryType);
}

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 w  ww .j a  v a 2 s  .  c o m

    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 {
    XPathFactory xPathFactory = XPathFactory.newInstance();
    XPath xPath = xPathFactory.newXPath();

    InputSource doc = new InputSource(new InputStreamReader(new FileInputStream(new File("file.xml"))));

    String expression = "//Home/data";
    XPathExpression xPathExpression = xPath.compile(expression);

    NodeList elem1List = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET);
    xPathExpression = xPath.compile("@type");

    for (int i = 0; i < elem1List.getLength(); i++) {
        System.out.println(xPathExpression.evaluate(elem1List.item(i), XPathConstants.STRING));
    }//from   w ww  .j av  a2 s  . c o m
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);/*  w w w. java2s  . c  o  m*/
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document dDoc = builder.parse("c:\\file.xml");
    XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new UniversalNamespaceResolver(dDoc));
    String query = "//rss/channel/yweather:location/@city";
    XPathExpression expr = xPath.compile(query);
    Object result = expr.evaluate(dDoc, XPathConstants.STRING);
    System.out.println(result);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String xml = "<root>" + "<ctc:BasePrice>" + "<cgc:PriceAmount currencyID='EUR'>18.75</cgc:PriceAmount>"
            + "<cgc:BaseQuantity quantityUnitCode='EA'>1</cgc:BaseQuantity>" + "</ctc:BasePrice>"
            + "<ctc:BasePrice>" + "<cgc:PriceAmount currencyID='EUR'>18.25</cgc:PriceAmount>"
            + "<cgc:BaseQuantity quantityUnitCode='EA'>1</cgc:BaseQuantity>"
            + "<cgc:MinimumQuantity quantityUnitCode='EA'>3</cgc:MinimumQuantity>" + "</ctc:BasePrice>"
            + "</root>";

    InputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document xmlDocument = builder.parse(xmlStream);
    XPath xPath = XPathFactory.newInstance().newXPath();
    String expression = "//*[local-name() = 'BasePrice' and not(descendant::*[local-name() = 'MinimumQuantity'])]/*[local-name()='PriceAmount']";
    NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < nodeList.getLength(); i++) {
        System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
    }/*from  w  w  w.j  a v  a 2  s  .com*/
}

From source file:ApplyXPathJAXP.java

public static void main(String[] args) {
    QName returnType = null;/*from  w ww .  j a v  a2s  .c  o  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 {
    XPath xPath = XPathFactory.newInstance().newXPath();
    FileInputStream file = new FileInputStream(new File("c:/data.xml"));

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

    DocumentBuilder builder = builderFactory.newDocumentBuilder();

    Document xmlDocument = builder.parse(file);

    XPathExpression expr = xPath.compile("//project/*");
    NodeList list = (NodeList) expr.evaluate(xmlDocument, XPathConstants.NODESET);
    for (int i = 0; i < list.getLength(); i++) {
        Node node = list.item(i);
        System.out.println(node.getNodeName() + "=" + node.getTextContent());
    }// www  . ja v a  2s.  c  om
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();

    String xml1 = "<xml><product><product_id>2</product_id></product><car><product_id>12345678</product_id></car></xml>";
    String xml2 = "<xml><product><product_id>2</product_id></product><car><car_type id_1=\"2\" id_2=\"32\">55555</car_type></car></xml>";

    Document doc1 = stringToDom(xml1);
    Document doc2 = stringToDom(xml2);

    XPathExpression expr1 = xpath.compile("//car/product_id/text()");
    String carId = (String) expr1.evaluate(doc1, XPathConstants.STRING);

    XPathExpression expr2 = xpath.compile("//car/car_type/text()");
    String carType = (String) expr2.evaluate(doc2, XPathConstants.STRING);

    System.out.println("carId: " + carId);
    System.out.println("carType: " + carType);

}

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();// w  ww  .  j a  v a 2s. c  o m
    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());
    }

}

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);/*from w ww .j a  v  a 2 s . c o  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");
}