Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to encode text data for XML in Java?

Tags:

java

xml

encoding

Very similar to this question, except for Java.

What is the recommended way of encoding strings for an XML output in Java. The strings might contain characters like "&", "<", etc.

like image 467
Epaga Avatar asked Jan 13 '09 15:01

Epaga


People also ask

How do you write data to XML file in Java?

Write XML to a file Steps to create and write XML to a file. Create a Document doc . Create XML elements, attributes, etc., and append to the Document doc . Create a Transformer to write the Document doc to an OutputStream .

Can we convert string to XML in Java?

Document convertStringToDocument(String xmlStr) : This method will take input as String and then convert it to DOM Document and return it. We will use InputSource and StringReader for this conversion.

How read and write data from XML in Java?

We must have followed the process to read an XML file in Java: Instantiate XML file: DOM parser loads the XML file into memory and consider every tag as an element. Get root node: Document class provides the getDocumentElement() method to get the root node and the element of the XML file.


2 Answers

As others have mentioned, using an XML library is the easiest way. If you do want to escape yourself, you could look into StringEscapeUtils from the Apache Commons Lang library.

like image 92
Fabian Steeg Avatar answered Sep 21 '22 00:09

Fabian Steeg


Very simply: use an XML library. That way it will actually be right instead of requiring detailed knowledge of bits of the XML spec.

like image 20
Jon Skeet Avatar answered Sep 23 '22 00:09

Jon Skeet