Question

I need to create an XML fragment and I am using Java DOM for this.

Any documentation I could find explains that one can use Element.setTextContent(), like so:

Integer someValue = 5;
Element element = myMethodCreatingTheElement();
element.setTextContent(String.valueOf(someValue));

My question is: is it enough to rely on String.valueOf() to represent the corresponding value correctly in XML?

Thanks in advance,

Was it helpful?

Solution

You can use javax.xml.bind.DatatypeConverter to convert XML text to/from Java data types (part of JDK/JRE since Java SE 6). This will ensure that XML specific things about the text representation are properly handled.

OTHER TIPS

Try for jsoup it's also good Java DOM

is it enough to rely on String.valueOf() to represent the corresponding value correctly in XML?

The DOM is an abstract data model for XML documents. When you call setTextContent() you're setting the value of the element (strictly speaking you're setting the children of the element to be a single text node with the specified value). When you write the DOM tree out as an XML document, it is the serializer's job to ensure that all the values are output in the correct representation.

As long as the value you're setting doesn't contain any characters that are forbidden in XML (control characters below U+0020 apart from tab, newline and carriage return, or unpaired surrogates) then you'll be fine, the serializer will perform any necessary escaping for you.

As for String.valueOf itself, its rules for converting primitive types to strings are laid out in detail in the JavaDoc documentation. With the above caveat about avoiding illegal characters if you're converting a char, char[] or an Object that overrides toString, the values produced by String.valueOf will always be legal in XML.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top