How to avoid encoding <,>, & with Document.createTextNode

 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 code above. The output is similar to 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 do not want the tags to be encoded. I need a conclusion like this.

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

Please help me with this.

Thanks Mohan

+3
source share
6 answers

Short answer

You can use the CDATA mechanism in XML to prevent escaping characters. The following is a sample DOM code:

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

Content will be:

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

LONG RESPONSE

The following is a complete example of using the CDATA section using the DOM API.

 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); } } 

Output

Note the difference in the foo and bar elements, although they have the same content. I 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> 
+4
source

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

You must 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()); } } } 
+3
source

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

SOAPMessage msg = messageContext.getMessage ();

header.setTextContent (seched);

Then use

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

Convert to string to get content

 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 string special characters

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

oposite string for dom with 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 install it back into the message with soap msg.getSOAPPart().setContent(src123);

+2
source

Do not use createTextNode - the whole point is to insert some text (like data) into the document, and not a piece of raw XML.

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

0
source

I do not want the tags to be encoded. I need a conclusion like this.

Then you don't need node text at all, so createTextNode doesn't work for you. (Rather, it works great - it just doesn't do what you want). You should probably just parse your XML string and then import the node document from the result into a new document.

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

It is possible that something like JDOM will make it easier, but that is the basic approach.

0
source

Mohan

You cannot use Document.createTextNode (). This method converts (or speeds up) the characteristics in your XML. Instead, you need to create two separate documents from 2 XML and use importNode.

I am using 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 

Then create the NodeList of the / Node element that you want to import. Create a Node from a NodeList. Create another Node of what you are going to import using importNode. Create 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 the standard Transformer - StringWriter for StreamResult to get the results.

0
source

Source: https://habr.com/ru/post/979268/


All Articles