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.

Qwerky
  • 18,217
  • 6
  • 44
  • 80
Ashwin
  • 12,691
  • 31
  • 118
  • 190

1 Answers1

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();
Phani
  • 5,319
  • 6
  • 35
  • 43
  • 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](http://www.java-tips.org/java-se-tips/org.w3c.dom/saving-a-dom-tree-to-xml-file-javax.xml.parsers-5.html) is really not hard to find. – Marko Topolnik Apr 12 '12 at 10:14
  • @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? – Ashwin Apr 12 '12 at 10:33
  • @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: http://stackoverflow.com/questions/5502526/org-w3c-dom-document-to-string – Phani Apr 12 '12 at 10:36
  • @Ashwin that is because of Indenting in the second line, remove that line, it would be normal. – Phani Apr 12 '12 at 10:36
  • @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. – Ashwin Apr 14 '12 at 06:20
  • It doesn't matter if attributes are in sequence, it will only makes problem if elements are jumbled and if you are going to validate against XSD. – Phani Apr 14 '12 at 08:25