5

使用此 XML 示例:

<A>
  <B>
    <id>0</id>
  </B>
  <B>
    <id>1</id>
  </B>
</A>

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

<B>
  <id>1</id>
</B>

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

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

4

2 回答 2

29

添加到 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());
}
于 2012-01-23T23:16:52.177 回答
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) + "]");
}
于 2012-01-23T23:10:38.017 回答