tags:

views:

120

answers:

2

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

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

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

+1  A: 

Once you've loaded the document into the DOM, there's no concept of "inner xml", only nodes of various types. You would have to re-serialize the subtree yourself to get a string.

More generally, there's an abstraction called "document", which can have different representations. What we call "XML" is merely one possible concrete representation of the abstract document. The tree of nodes in a DOM representation is another, closer to the structure of the abstract document.

Jim Garrison
+2  A: 

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.

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 http://stackoverflow.com/questions/35785/xml-serialization-in-java

Robert Diana