Java如何提取完整的XML块

发布于 2024-12-28 16:47:27 字数 651 浏览 0 评论 0 原文

使用这个 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 节点集 和 < a href="https://stackoverflow.com/questions/3093347/how-can-i-extract-an-xml-block-from-an-xml-document">如何从 XML 中提取 XML 块文件?

Using this XML example:

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

I want a simple method to extract the XML block of node B, returning the XML String:

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

To retrieve this node i should use some Java XPath library like XOM or Java XPath, but i couldn't find how to get the complete XML string.

I found two equivalent answered questions using C#:
C# How to extract complete xml node set and how can I extract an XML block from an XML document?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

相思碎 2025-01-04 16:47: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());
}

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 = "<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());
}
半世蒼涼 2025-01-04 16:47:27

引用第二个 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) + "]");
}

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) + "]");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文