简体   繁体   中英

Append XML String to Element in Java

I have a requirement in which I need to append a XML String to Element in Java. Below code shows what I am doing now:

Document doc;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
Element row = doc.createElement("Row");
results.appendChild(row);
String columnName = "XML_00805F49916B";
String valueString = "<IBS><Product></Product></IBS>";
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(valueString));
row.appendChild(node);

DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StringWriter sw = new StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
retMsg = sw.toString();
System.out.println("SQL Return message: " + retMsg);

The above code returns output:

SQL Return message: <Results><Row><XML_00805F49916B>&lt;IBS&gt;&lt;Product&gt;&lt;/Product&gt;&lt;/IBS&gt;</XML_00805F49916B></Row></Results>

But, I want the output to be:

SQL Return message: <Results><Row><XML_00805F49916B><IBS><Product></Product></IBS></XML_00805F49916B></Row></Results>

Please can I have some help how to get the required output?

A text node is not part of an XML document's structure. It's just text. The special characters < , > , and & are just characters when it comes to text nodes, though the final XML representation will need to escape them.

You cannot accomplish your goal by inserting a text node. You need to insert elements.

From your comment:

Unfortunately I am getting that XML ie valueString from external source, and its schema would be different all times. I need a generic way of adding a XML string value into Element

You can parse arbitrary XML content into a new XML document, and then import (copy) the new document's root element to your document:

String columnName = "XML_00805F49916B";
String valueString = "<IBS><Product></Product></IBS>";
Element node = doc.createElement(columnName);

Document valueDoc = builder.parse(
    new InputSource(new StringReader(valueString)));
Node valueElement = doc.importNode(valueDoc.getDocumentElement(), true);
node.appendChild(valueElement);

row.appendChild(node);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM