如何获取节点值及其子节点?例如,我将以下节点解析为 dom Document
实例:
<root>
<ch1>That is a text with <value name="val1">value contents</value></ch1>
</root>
我使用 xpath 选择 ch1 节点。现在我需要获取它的内容,即 <ch1>
之间包含的所有内容。和</ch1>
,例如That is a text with <value name="val1">value contents</value>
.
我该怎么做?
最佳答案
我发现以下使用转换的代码片段,它几乎给出了我想要的。可以通过改变输出方法来调整结果。
public static String serializeDoc(Node doc) {
StringWriter outText = new StringWriter();
StreamResult sr = new StreamResult(outText);
Properties oprops = new Properties();
oprops.put(OutputKeys.METHOD, "xml");
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = null;
try {
t = tf.newTransformer();
t.setOutputProperties(oprops);
t.transform(new DOMSource(doc), sr);
} catch (Exception e) {
System.out.println(e);
}
return outText.toString();
}
关于java - 获取节点原始文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8873393/