In this example we shall show you how to add CDATASection to a DOM Document. We have implemented a method, that is void prettyPrint(Document xml)
, in order to convert a DOM into a formatted XML String. To add CDATASection to a DOM Document one should perform the following steps:
- Obtain a new instance of a DocumentBuilderFactory, that is a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents.
- Set the parser produced so as not to validate documents as they are parsed, using
setValidating(boolean validating)
API method of DocumentBuilderFactory, with validating set to false. - Create a new instance of a DocumentBuilder, using
newDocumentBuilder()
API method of DocumentBuilderFactory. - Parse the FileInputStream with the content to be parsed, using
parse(InputStream is)
API method of DocumentBuilder. This method parses the content of the given InputStream as an XML document and returns a new DOM Document object. - Get the Document Element using
getDocumentElement()
API method of Document. - Create a CDATASection node whose value is the specified string, with
createCDATASection(String data)
API method of Document. - Append the node to the document element, using
appendChild(Node newChild)
API method of Node. - Call
void prettyPrint(Document xml)
method of the example. The method gets the xml Document and converts it into a formatted xml String, after transforming it with specific parameters, such as encoding. The method uses a Transformer, that is created usingnewTransformer()
API method of TransformerFactory. The Transformer is used to transform a source tree into a result tree. After setting specific output properties to the transformer, usingsetOutputProperty(String name, String value)
API method of Transformer, the method uses it to make the transformation, withtransform(Source xmlSource, Result outputTarget)
API method of Transformer. The parameters are the DOMSource with the DOM node and the result that is a StreamResult created from a StringWriter,
Read full article from Add CDATA section to DOM document | Examples Java Code Geeks
No comments:
Post a Comment