获取节点原始文本 [英] get node raw text

查看:36
本文介绍了获取节点原始文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过其子节点获取节点值?例如,我将以下节点解析为dom Document 实例:

How get node value with its children nodes? For example I have following node parsed into dom Document instance:

<root>
    <ch1>That is a text with <value name="val1">value contents</value></ch1>
</root>

我使用xpath选择ch1节点。现在,我需要获取它的内容,以及< ch1> < / ch1> 之间的所有内容,例如这是具有< value name = val1> value内容< / value> 的文本。

I select ch1 node using xpath. Now I need to get its contents, everything what is containing between <ch1> and </ch1>, e.g. That is a text with <value name="val1">value contents</value>.

我该怎么办?

推荐答案

我发现以下使用转换的代码段几乎可以完全满足我的需求。可以通过更改输出方法来调整结果。

I have found the following code snippet that uses transformation, it gives almost exactly what I want. It is possible to tune result by changing output method.

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

这篇关于获取节点原始文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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