How can an XML document like this be created with the JAXP API?

M.Kumar Sankar

To generate an XML document using Jaxp the following sample code can help you.

import java.io.*;

import javax.xml.parsers.*;

import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import org.w3c.dom.Text;

import com.sun.xml.parser.DocumentBuilderFactoryImpl;
import com.sun.xml.parser.*;
import com.sun.xml.tree.*;	

public class JaxpDoc
{
	public static void main(String a[])
	{
		try{
		 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.newDocument();

		Element root = doc.createElement("root");
		Element address = doc.createElement("address");
		Element name = doc.createElement("name");
		name.setAttribute("City","New York");
		Element first = doc.createElement("first");
		first.appendChild(doc.createTextNode("John"));
		Element last = doc.createElement("last");
		last.appendChild(doc.createTextNode("Joe"));
		name.appendChild(first);
		name.appendChild(last);
		address.appendChild(name);
		root.appendChild(address);
		doc.appendChild(root);
		XmlDocument tdoc = (XmlDocument)doc;
		tdoc.write(new PrintWriter(System.out));
		System.out.println("Document created successfully ...");
		} catch(Exception e)
			{	
				e.printStackTrace(); 
			}
	}
}

Note that it is one way. You can use XmlDocument object directly to get an Docuemnt instance and use the above same methods to generate document. You can place it in a loop so that any number of address nodes can be created.
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact