/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. import java.io.File

2. import javax.xml.parsers.*; 

3. import org.w3c.dom.*; 

4. import javax.xml.transform.*; 

5. import javax.xml.transform.dom.*; 

6. import javax.xml.transform.stream.*; 

7.  

8. public class Dom2File

9.   public static void main(String[] args) { 

10.     try

11.       DocumentBuilder db; 

12.       db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 

13.       Document doc = db.newDocument(); 

14.       Element rootelm = doc.createElement("rootie"); 

15.       doc.appendChild(rootelm); 

16.        

17.       Node tay =doc.createTextNode("ay"); 

18.       Node tbee =doc.createTextNode("bee"); 

19.       Node tsea =doc.createTextNode("sea"); 

20.        

21.       Element elm2 = doc.createElement("aliment2"); 

22.       Element elm3 = doc.createElement("aliment3"); 

23.       Element elm4 = doc.createElement("aliment4"); 

24.       Element elm5 = doc.createElement("aliment5"); 

25.        

26.       rootelm.appendChild(elm3); 

27.       elm3.appendChild(tbee); 

28.  

29.       rootelm.insertBefore(elm2, elm3); 

30.       elm2.appendChild(tay); 

31.       elm2.setAttribute("atreebeauty", "Valyou"); 

32.  

33.       rootelm.getLastChild().appendChild(elm5); 

34.       elm3.appendChild(elm4); 

35.  

36.       rootelm.getFirstChild().getNextSibling().appendChild(elm5); 

37.       rootelm.getLastChild().getLastChild().appendChild(tsea); 

38.  

39.       Comment cm = doc.createComment("oh my, Steorn's ORBO"); 

40.       doc.insertBefore(cm, rootelm); 

41.        

42.       DOMSource src = new DOMSource(doc); 

43.       File f = new File("dom2file.xml"); 

44.       StreamResult out = new StreamResult(f); 

45.       Transformer tf = TransformerFactory.newInstance().newTransformer(); 

46.       tf.transform(src, out); 

47.     } 

48.     catch (Exception exc) { 

49.       exc.printStackTrace(); 

50.     } 

51.   } 

52.

53. /* ===  dom2file.xml ============ 

54. <?xml version="1.0" encoding="UTF-8"?> 

55. <!--oh my, Steorn's ORBO--> 

56. <rootie> 

57.   <aliment2 atreebeauty="Valyou">ay</aliment2> 

58.   <aliment3> 

59.     bee 

60.     <aliment4 /> 

61.     <aliment5>sea</aliment5> 

62.   </aliment3> 

63. </rootie> 

64.  

65. */