How to read XML using XPath in Java

后端 未结 8 1405
无人及你
无人及你 2020-11-21 05:38

I want to read XML data using XPath in Java, so for the information I have gathered I am not able to parse XML according to my requirement.

here is what I want to do

8条回答
  •  無奈伤痛
    2020-11-21 06:18

    If you have a xml like below

    
        
            
                
                    Testabc
                    12121
                    Testpqr
                
            
        
        
            
                12--abc--pqr
            
        
    
    

    and wanted to extract the below xml

    
       
          
             Testabc
             12121
             Testpqr
          
       
    
    

    The below code helps to achieve the same

    public static void main(String[] args) {
    
        File fXmlFile = new File("C://Users//abhijitb//Desktop//Test.xml");
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document document;
        Node result = null;
        try {
            document = dbf.newDocumentBuilder().parse(fXmlFile);
            XPath xPath = XPathFactory.newInstance().newXPath();
            String xpathStr = "//Envelope//Header";
            result = (Node) xPath.evaluate(xpathStr, document, XPathConstants.NODE);
            System.out.println(nodeToString(result));
        } catch (SAXException | IOException | ParserConfigurationException | XPathExpressionException
                | TransformerException e) {
            e.printStackTrace();
        }
    }
    
    private static String nodeToString(Node node) throws TransformerException {
        StringWriter buf = new StringWriter();
        Transformer xform = TransformerFactory.newInstance().newTransformer();
        xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        xform.transform(new DOMSource(node), new StreamResult(buf));
        return (buf.toString());
    }
    

    Now if you want only the xml like below

    
       
          Testabc
          12121
          Testpqr
       
    
    

    You need to change the

    String xpathStr = "//Envelope//Header"; to String xpathStr = "//Envelope//Header/*";

提交回复
热议问题