0

I am using the follwing code to change a xml document:

DocumentBuilderFactory fty1 = DocumentBuilderFactory.newInstance();
   fty1.setNamespaceAware(true);
   DocumentBuilder builder1 = fty1.newDocumentBuilder();
   ByteArrayInputStream bais1 = new ByteArrayInputStream(tr1.getBytes());//tr1=xml string
   Document xmldoc1=builder1.parse(bais1);
   xmldoc1.getElementsByTagName("userID").item(0).setTextContent("123123132");


The xmldoc1 contains the changed form. Now how convert it to a string so that the new doument can be passed to others.

1 Answer 1

4
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");        
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(xmldoc1);
transformer.transform(source, result);
String xmlString = sw.toString();
Sign up to request clarification or add additional context in comments.

6 Comments

Khm... that's XSLT code :) It would have been more obvious if you included the line that initializes trans. The guy should really google it for himself. For example this one here is really not hard to find.
@Phani : thank you. But there is a slight difference. In the new xml string, the element whose content has been set, is coming in new line. This might create a different signature(I using xml signatures). Why is this happening?
@MarkoTopolnik As per StackOverflow recommendations, we should search for the question if didn't find then we should report. But still the same questions are getting repeated.Few references: stackoverflow.com/questions/5502526/…
@Ashwin that is because of Indenting in the second line, remove that line, it would be normal.
@Phani : I have one more doubt. In this process of conversion is the original document copied as such to the string? because after conversion the new xml string is jumbled. I mean the attributes are jumbled.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.