Java如何提取完整的XML块 [英] Java How to extract a complete XML block

查看:282
本文介绍了Java如何提取完整的XML块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此XML示例:

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

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

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

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

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

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.

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

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?

推荐答案

添加到lwburk的解决方案,要将DOM节点转换为字符串形式,您可以使用变形金刚

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

完整示例:

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

这篇关于Java如何提取完整的XML块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆