我希望我的XML节点为:
<Name><![CDATA[Masonry, Stucco & Brick Paint]]></Name>
但它被保存为:
<Name><![CDATA[Abcd, City & Abcd]]></Name>
我使用的代码如下:
import org.w3c.dom.Document;
import org.w3c.dom.Element;
...
...
Element name = doc.createElement("Name");
name.appendChild(doc.createTextNode("<![CDATA[" + categoryName + "]]>"));
category.appendChild(name);
我甚至尝试使用&#34; amp; lt;&#34;和&#34; amp; gt;&#34; for&lt;和&gt;分别但不起作用
答案 0 :(得分:0)
你可以试试这个......
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;
}
}