Java How to extract a complete XML block

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

Using this XML example:


  
    0
  
  
    1
  

<         


        
2条回答
  •  臣服心动
    2020-12-03 09:56

    The expression needed to refer to that second B element should look something like this:

    /*/B[id='1']
    

    Or, if the target node is at an unknown position in the document, use:

    //B[id='1']
    

    Full Java example (assuming the XML is in a file called workbook.xml):

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse("workbook.xml");
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//B[id='1']");        
    
    NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        System.out.println("[" + nodes.item(i) + "]");
    }
    

提交回复
热议问题