使用此XML示例:
<A>
<B>
<id>0</id>
</B>
<B>
<id>1</id>
</B>
</A>
我想要一个简单的方法来提取节点B的XML块,返回XML String:
<B>
<id>1</id>
</B>
要检索此节点,我应该使用一些Java XPath库,如XOM或Java XPath,但我找不到如何获取完整的XML字符串。
我使用C#找到了两个等效的回答问题: C# How to extract complete xml node set和how can I extract an XML block from an XML document?
答案 0 :(得分:27)
添加到lwburk的解决方案,要将DOM节点转换为字符串形式,您可以使用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 = "<A><B><id>0</id></B><B><id>1</id></B></A>";
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());
}
答案 1 :(得分:5)
引用第二个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) + "]");
}