gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:50:28 24 4
gpt4 key购买 nike

我的问题不是关于 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();

我正在为如何获得一个代表 xml 的 subtree 的字符串而苦苦挣扎,该字符串以 <some> 开头标签。换句话说,我要写什么代码来获得一个字符串,当打印出来时,会打印出以下内容? xpath 查询将是“/wrapper/data/some”,但我不知道如何适本地使用 xpath api。

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

最佳答案

您只需使用 Transformer 将从 XPathExpression 返回的 Node 转换为 String就像您将文档写入文件一样,这里是一个完整的示例:

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

关于Java XPath API - 获取表示子树的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21661304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com