7512

How to avoid encoding of ,& with Document.createTextNode

Question:

class XMLencode { public static void main(String[] args) { try{ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement("roseindia"); doc.appendChild(root); Text elmnt=doc.createTextNode("<data>sun</data><abcdefg/><end/>"); root.appendChild(elmnt); TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer(); Source src = new DOMSource(doc); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); }catch(Exception e){ System.out.println(e.getMessage()); } } }

Here is my above piece of code. The output generated is like this

<?xml version="1.0" encoding="UTF-8" standalone="no"?><roseindia>&lt;data&gt;sun&lt;/data&gt;&lt;abcdefg/&gt;&lt;end/&gt;</roseindia>

I dont want the tags to be encoded. I need the output in this fashion.

<?xml version="1.0" encoding="UTF-8" standalone="no"?><roseindia><data>sun</data><abcdefg/><end/></roseindia>

Please help me on this.

Thanks, Mohan

Answer1:

<strong>Short Answer</strong>

You could leverage the CDATA mechanism in XML to prevent characters from being escaped. Below is an example of the DOM code:

doc.createCDATASection("<foo/>");

The content will be:

<![CDATA[<foo/>]]> <hr />

<strong>LONG ANSWER</strong>

Below is a complete example of leveraging a CDATA section using the DOM APIs.

package forum12525152; import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.*; public class Demo { public static void main(String[] args) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.newDocument(); Element rootElement = document.createElement("root"); document.appendChild(rootElement); // Create Element with a Text Node Element fooElement = document.createElement("foo"); fooElement.setTextContent("<foo/>"); rootElement.appendChild(fooElement); // Create Element with a CDATA Section Element barElement = document.createElement("bar"); CDATASection cdata = document.createCDATASection("<bar/>"); barElement.appendChild(cdata); rootElement.appendChild(barElement); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(System.out); t.transform(source, result); } }

<em><strong>Output</strong></em>

Note the difference in the foo and bar elements even though they have similar content. I have formatted the result of running the demo code to make it more readable:

<?xml version="1.0" encoding="UTF-8" standalone="no"?> <root> <foo>&lt;foo/&gt;</foo> <bar><![CDATA[<bar/>]]></bar> </root>

Answer2:

Instead of writing like this doc.createTextNode("<data>sun</data><abcdefg/><end/>");

You should create each element.

import javax.xml.parsers.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import org.w3c.dom.*; class XMLencode { public static void main(String[] args) { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder docBuilder = factory.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement("roseindia"); doc.appendChild(root); Element data = doc.createElement("data"); root.appendChild(data); Text elemnt = doc.createTextNode("sun"); data.appendChild(elemnt); Element data1 = doc.createElement("abcdefg"); root.appendChild(data1); //Text elmnt = doc.createTextNode("<data>sun</data><abcdefg/><end/>"); //root.appendChild(elmnt); TransformerFactory tranFactory = TransformerFactory.newInstance(); Transformer aTransformer = tranFactory.newTransformer(); Source src = new DOMSource(doc); Result dest = new StreamResult(System.out); aTransformer.transform(src, dest); } catch (Exception e) { System.out.println(e.getMessage()); } } }

Answer3:

You can use the doc.createTextNode and use a workaround (long) for the escaped characters.

SOAPMessage msg = messageContext.getMessage();

header.setTextContent(seched);

Then use

Source src = msg.getSOAPPart().getContent();

To get the content, the transform it to string

TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer. setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StreamResult result1 = new StreamResult(new StringWriter()); transformer.transform(src, result1);

Replace the string special characters

String xmlString = result1.getWriter().toString() .replaceAll("&lt;", "<"). replaceAll("&gt;", ">"); System.out.print(xmlString);

the oposite string to dom with the fixed escaped characters

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xmlString)); Document doc = db.parse(is); Source src123 = new DOMSource(doc);

Then set it back to the soap message msg.getSOAPPart().setContent(src123);

Answer4:

Don't use createTextNode - the whole point of it is to insert some text (as data) into the document, not a fragment of raw XML.

Use a combination of createTextNode for the text and createElement for the elements.

Answer5:

<blockquote>

I dont want the tags to be encoded. I need the output in this fashion.

</blockquote>

Then you <em>don't</em> want a text node at all - which is why createTextNode isn't working for you. (Or rather, it's working fine - it's just not doing what you want). You should probably just parse your XML string, then import the document node from the result into your new document.

Of course, if you know the elements beforehand, don't express them as text in the first place - use a mixture of createElement, createAttribute, createTextNode and appendChild to create the structure.

It's entirely possible that something like <a href="http://jdom.org/" rel="nofollow">JDOM</a> will make this simpler, but that's the basic approach.

Answer6:

Mohan,

You can't use Document.createTextNode(). That methos transforms (or escapes) the charactes in your XML. Instead, you need to build two separate Documents from the 2 XML's and use <em>importNode</em>.

I use Document.importNode() like this to solve my problem:

Build your builders:

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = dbf.newDocumentBuilder(); Document oldDoc = builder.parse(isOrigXml); //this is XML as InputSource Document newDoc = builder.parse(isInsertXml); //this is XML as InputSource

Next, build a NodeList of the Element/Node you want to import. Create a Node from the NodeList. Create another Node of what you are going to import using importNode. Build the last Node of the final XML as such:

NodeList nl = newDoc.getElementByTagName("roseindia"); //or whatever the element name is Node xmlToInsert = nl.item(0); Node importNode = oldDoc.importNode(xmlToImport, true); Node target = ((NodeList) oldDoc.getElementsByTagName("ELEMENT_NAME_OF_LOCATION")).item(0); target.appendChild(importNode); Source source = new DOMSource(target); ....

The rest is standard Transformer - StringWriter to StreamResult stuff to get the results.

Recommend

  • AS3 String Memory Leak
  • JavaScript In KML Ignored By Google Earth Plugin
  • grep: matching on literal “+”
  • Escape special characters in MySQL using C# and ASP.Net
  • Tag and Element shortcuts - Sublime Text 2
  • MongoDB Compass Visually Insert Sub-Document
  • How does CoreLocation locate the device?
  • How to set infinite shared access signature policy in azure?
  • Base64 as method of sanitizing user input for Mysql
  • how to display   in Mozilla using XSL.
  • Wait for .each() .getJSON request to finish before executing a callback
  • custom string delimiters stringtemplate-4
  • How to change placeholder text in an autocomplete activity of android google place?
  • Manually Timing out a C# Thread
  • Upgrade project from WorkLight 6.1 to MobileFirst 7.1
  • Changing media screen makes div overlay
  • How to add closing tag for canvas in three js rendered Canvas?
  • Get the pasted content on document on paste event
  • change search magnifying glass to UIActivityIndicatorView
  • Magento get URL before current
  • Consuming a WCF service in a Java Client using wsHttpBinding
  • Validate jQuery plugin, field not required
  • Prevent Tomcat from caching request during starup
  • Bash if statement with multiple conditions
  • where do I find the xml.dom python package for the python-2.6.0-8.9.28 and I have a suse/x86_64 vers
  • How to make JSON.NET deserialize to Microsoft Date Time?
  • How do I signal completion of my dataflow?
  • Tamper-proof configuration files in .NET?
  • How to use JavaScript to determine whether a file exists in a directory?
  • print() is showing quotation marks in results
  • Content-Length header not returned from Pylons response
  • Play WS (2.2.1): post/put large request
  • How to access EntityManager inside Entity class in EJB3
  • Deserializing XML into class C#
  • vba code to select only visible cells in specific column except heading
  • When should I choose bucket sort over other sorting algorithms?
  • How can I estimate amount of memory left with calling System.gc()?
  • Is there a mandatory requirement to switch app.yaml?
  • using HTMLImports.whenReady not working in chrome
  • How to Embed XSL into XML