0

I am trying to store XML string in XML file in the following way

String appData =  "<Data><element><displayname>John</displayname></element></Data>";


org.w3c.dom.Element appData= doc.createElement("appData");
rootElement.appendChild(appData);
org.w3c.dom.Element appXmlData= doc.createElement("myData");
appData.appendChild(appXmlData);
appXmlData.setTextContent(appData);

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(path1));
transformer.transform(source, result);

the data is stored in the xml as

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<appData>
<myData>
      &lt;Data&gt;&lt;element&gt;&lt;displayname&gt;John&lt;/displayname&gt;&lt;/element&gt;&lt;/Data&gt;
</myData>

What i want is

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<appData>
<myData>
    <Data><element><displayname>John</displayname></element></Data>
</myData>

Help me in achieving this

3
  • 1
    You can't as "<" ">" are special keywords for XML, they can't appear in it's content. Instead they are replaced with &lt; and &gt; respectively. Any xml containing "<" ">" as values in any content will not be a proper XML and will fail validation Commented Nov 24, 2014 at 13:31
  • read more here: xml.silmaril.ie/specials.html Commented Nov 24, 2014 at 13:33
  • You can use CDATA & add your String inside myData in that then only it will retains < & > symbols. Commented Nov 24, 2014 at 13:34

1 Answer 1

1

Like you did a

org.w3c.dom.Element appXmlData= doc.createElement("myData");

you have to create child elements for your other nodes:

org.w3c.dom.Element dataNode= doc.createElement("Data");
appXmlData.appendChild(dataNode);

and so on...Since you are using the dom api, it will escape the xml content in your node.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes I can do this way.but the thing is i have a large xml string which is making me to look for an alternative

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.