I want my XML node as :
<Name><![CDATA[Masonry, Stucco & Brick Paint]]></Name>
But it is getting saved as :
<Name><![CDATA[Abcd, City & Abcd]]></Name>
I am using code like:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
...
...
Element name = doc.createElement("Name");
name.appendChild(doc.createTextNode("<![CDATA[" + categoryName + "]]>"));
category.appendChild(name);
I even tried using "amp;lt;" and "amp;gt;" for < and > respectively but does not works
You can try this...
class StringToDocumentToString {
public static void main(String[] args) {
final String xmlStr = "<Name><![CDATA[Masonry, Stucco & Brick Paint]]></Name>";
Document doc = convertStringToDocument(xmlStr); //You can directly store this document as .xml but if you want String as return than do next step
String str = convertDocumentToString(doc);
System.out.println(str);
}
private static String convertDocumentToString(Document doc) {
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer;
try {
transformer = tf.newTransformer();
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(doc), new StreamResult(writer));
String output = writer.getBuffer().toString();
return output;
} catch (TransformerException e) {
e.printStackTrace();
}
return null;
}
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document doc = builder.parse(new InputSource(new StringReader(
xmlStr)));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.