在Java DOM中获取节点的内部XML作为String [英] Get a node's inner XML as String in Java DOM

查看:88
本文介绍了在Java DOM中获取节点的内部XML作为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个XML org.w3c.dom.Node,如下所示:

I have an XML org.w3c.dom.Node that looks like this:

<variable name="variableName">
    <br /><strong>foo</strong> bar
</variable>

如何获取< br />< strong> FOO< /强> bar part as a String?

How do I get the <br /><strong>foo</strong> bar part as a String?

推荐答案

org.w3c.dom中没有简单的方法。节点为此。 getTextContent()给出每个子节点连接在一起的文本。 getNodeValue()将为您提供当前节点的文本,如果它是属性,CDATA或文本节点。因此,您需要使用getChildNodes(),getNodeName()和getNodeValue()的组合来序列化节点来构建字符串。

There is no simple method on org.w3c.dom.Node for this. getTextContent() gives the text of each child node concatenated together. getNodeValue() will give you the text of the current node if it is an Attribute, CDATA or Text node. So you would need to serialize the node using a combination of getChildNodes(), getNodeName() and getNodeValue() to build the string.

您还可以使用一个存在的各种XML序列化库。有XStream甚至JAXB。 Java中的XML序列化中讨论了这一点。

You can also do it with one of the various XML serialization libraries that exist. There is XStream or even JAXB. This is discussed in XML serialization in Java?

这篇关于在Java DOM中获取节点的内部XML作为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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