Java How to extract a complete XML block

前端 未结 2 1662
面向向阳花
面向向阳花 2020-12-03 09:24

Using this XML example:


  
    0
  
  
    1
  

<         


        
2条回答
  •  佛祖请我去吃肉
    2020-12-03 10:04

    Adding to lwburk's solution, to convert a DOM Node to string form, you can use a Transformer:

    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());
    }
    

    Complete example:

    public static void main(String... args)
    throws Exception
    {
        String xml = "01";
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        Document doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
    
        XPath xPath = XPathFactory.newInstance().newXPath();
        Node result = (Node)xPath.evaluate("A/B[id = '1']", doc, XPathConstants.NODE);
    
        System.out.println(nodeToString(result));
    }
    
    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());
    }
    

提交回复
热议问题