Link to home
Start Free TrialLog in
Avatar of fsyed
fsyed

asked on

Need to save an XML file from Java

Dear fellow Java developers:

I have written some java code that creates an xml document, but I'm having trouble SAVING it on to my local pc as an xml file.  I thought it would be similar to writing a text file, but I am a bit off.  I have listed my code below, and I think I'm almost there, but not quite.  When I run my code, I get the following content within my document.xml file:

[#document: null]

Any help would be greatly appreciated.  Thanks to all who reply.
package com.javatest;
 
import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
 
public class CreateXMLDoc {
	
	PrintWriter updates;
	
	public static void main(String[] args) throws Exception {
		String root = "transmission";
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
		Element rootElement = document.createElement(root);
        document.appendChild(rootElement);
		
		
			String element = "message";
			
			String data = "text";
			Element em = document.createElement(element);
			em.appendChild(document.createTextNode(data));
			rootElement.appendChild(em);
		
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(document);
        StreamResult result =  new StreamResult(System.out);
        transformer.transform(source, result);
        
        CreateXMLDoc testCode = new CreateXMLDoc();
        testCode.fileWrite(document);
	}
        
        public void fileWrite(Document doc){
        
        try  
        {     
        	updates = new PrintWriter(new BufferedWriter(new FileWriter("c:\\document.xml")), true);
        }  
        catch(Exception e)
        {   e.printStackTrace();
             return;
        }
        updates.println(doc);
	}
 
}

Open in new window

SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of fsyed
fsyed

ASKER

Thanks so much for your responses, and your solutions.  I do appreciate it!