Java XPath API - 获取表示子树的字符串

时间:2014-02-09 15:58:19

标签: java xml xpath subtree

我的问题不是关于xpath语法,它与围绕xpath的java API有关。请考虑以下xml:

<wrapper>
    <metadata>
        <somefield>somevalue</somefield>
        <anotherfield>othervalue</anotherfield>
    </metadata>
    <data>
        <some>
            <unique>
                <xml>
                    <structure>stuff</structure>
                </xml>
            </unique>
        </some>
    </data>
</wrapper>

我可以使用以下代码轻松获取使用xpath的元数据字段:

 XPath xp = XPathFactory.newInstance().newXPath();
 Node node = (Node) xp.evaluate("/wrapper/metadata/somefield", xmlDoc, XPathConstants.NODE);
 String somefield = node.getFirstChild().getNodeValue();

我正在努力学习如何从<some>标记开始获取表示xml的子树的字符串。换句话说,我编写什么代码来获取一个字符串,打印出来时会打印出以下内容? xpath查询将是&#34; / wrapper / data / some&#34;,但我不知道如何正确使用xpath api。

<some>
    <unique>
        <xml>
            <structure>stuff</structure>
        </xml>
    </unique>
</some>

1 个答案:

答案 0 :(得分:5)

您只需要使用NodeXPathExpressionString转换为Transformer,就像将文档写入文件一样,这是一个完整的例子:

public static void main(String[] args) throws Exception {
    final String xml = "<wrapper>\n"
            + "    <metadata>\n"
            + "        <somefield>somevalue</somefield>\n"
            + "        <anotherfield>othervalue</anotherfield>\n"
            + "    </metadata>\n"
            + "    <data>\n"
            + "        <some>\n"
            + "            <unique>\n"
            + "                <xml>\n"
            + "                    <structure>stuff</structure>\n"
            + "                </xml>\n"
            + "            </unique>\n"
            + "        </some>\n"
            + "    </data>\n"
            + "</wrapper>";
    final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8)));
    final XPathExpression xpath = XPathFactory.newInstance().newXPath().compile("//some");
    final Node node = (Node) xpath.evaluate(doc, XPathConstants.NODE);
    StringWriter sw = new StringWriter();
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.transform(new DOMSource(node), new StreamResult(sw));
    System.out.println(sw.toString());
}