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.
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 .
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.
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.
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.
Very simply: use an XML library. That way it will actually be right instead of requiring detailed knowledge of bits of the XML spec.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With