Java如何提取完整的XML块

使用此XML示例:

  0   1   

我想要一个简单的方法来提取节点B的XML块,返回XML String:

  1  

要检索此节点,我应该使用一些Java XPath库,如XOM或Java XPath,但我找不到如何获取完整的XML字符串。

我使用C#找到了两个等效的回答问题: C#如何提取完整的xml节点集 , 如何从XML文档中提取XML块?

添加到lwburk的解决方案,要将DOM节点转换为字符串forms,您可以使用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()); } 

完整的例子:

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

引用第二个B元素所需的表达式应如下所示:

 /*/B[id='1'] 

或者,如果目标节点位于文档中的未知位置,请使用:

 //B[id='1'] 

完整Java示例(假设XML位于名为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) + "]"); }