XPath with namespace in Java

前端 未结 2 1109
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 07:30

I would like to get all the content in between the tags but I do not know how to do this because of the urn: namespace.



        
2条回答
  •  无人及你
    2020-11-27 07:59

    XML xpath with Namespace

    Simple XML

    String namespaceXML = "Deep34Male  Kumar24Male Deepali19Female";
    String jsonString = "{}";
    String expression = "//information";
    

    Name space XML

    String namespaceXML = "nine hundred and ninety nine dollars";
    String jsonString = "{'soap':'http://schemas.xmlsoap.org/soap/envelope/', 'm':'http://www.dataaccess.com/webservicesserver/'}";
    String expression = "//m:NumberToDollarsResponse/m:NumberToDollarsResult/text()";
    

    Supply namespace xml file as a string, to asscerionXpath(namespaceXML, jsonString, expression) method and get result in the form of text/node.

    text() : nine hundred and ninety nine dollars

    node : nine hundred and ninety nine dollars

    public static String asscerionXpath(String namespaceXML, String jsonString, String expression){
        if(namespaceXML.indexOf("><") > -1) namespaceXML = namespaceXML.replace("><", ">\r\n<");
        if(jsonString.indexOf("'") > -1)    jsonString = jsonString.replace("'", "\"");
    
        System.out.println("namespaceXML : \n"+namespaceXML);
        System.out.println("nsmespaces : \n"+jsonString);
    
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(true);
        factory.setIgnoringComments(true);
        factory.setIgnoringElementContentWhitespace(true);
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document source = builder.parse( string2Source(namespaceXML) );
            XPath xpath = XPathFactory.newInstance().newXPath();
    
            addNameSpaces(jsonString, xpath);
            // An XPath expression is not thread-safe. Make sure it is accessible by only one Thread.
            XPathExpression expr = xpath.compile(expression);
    
            // The NodeList interface provides the abstraction of an ordered collection of nodes,
            NodeList nodes = (org.w3c.dom.NodeList) expr.evaluate(source, XPathConstants.NODESET);;
            Node tree_base = nodes.item(0);
            return document2String(tree_base);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (XPathExpressionException e) {
            System.out.println("If the expression cannot be evaluated.");
        }
        return "";
    }
    static InputSource string2Source( String str ) {
        InputSource inputSource = new InputSource( new StringReader( str ) );
        return inputSource;
    }
    static void addNameSpaces(String jsonString, XPath xpath) {
        JSONParser parser = new JSONParser();
        try {
            JSONObject namespaces = (JSONObject) parser.parse(jsonString);
    
            if (namespaces.size() > 0) {
                final JSONObject declaredPrefix = namespaces; // To access in Inner-class.
                NamespaceContext nameSpace = new NamespaceContext() {
                    // To get all prefixes bound to a Namespace URI in the current scope, XPath 1.0 specification
                    // --> "no prefix means no namespace"
                    public String getNamespaceURI(String prefix) {
                        Iterator key = declaredPrefix.keySet().iterator();
                        System.out.println("Keys : "+key.toString());
                        while (key.hasNext()) {
                            String name = key.next().toString();
                            if (prefix.equals(name)) {
                                System.out.println(declaredPrefix.get(name));
                                return declaredPrefix.get(name).toString();
                            }
                        }
                        return "";
                    }
                    public Iterator getPrefixes(String val) {
                        return null;
                    }
                    public String getPrefix(String uri) {
                        return null;
                    }
                };// Inner class.
    
                xpath.setNamespaceContext( nameSpace );
            }
    
        } catch ( org.json.simple.parser.ParseException e) {
            e.printStackTrace();
        }
    }
    

提交回复
热议问题