How to create XML file in Java

Posted: February 28, 2012 in Java Posts
Tags: , , , , ,

DOM provides many handy classes to create XML file easily. Firstly, you have to create a Document with DocumentBuilder class, define all the XML content – node, attribute with Element class. In last, use Transformer class to output the entire XML content to stream output, typically a File.

In this tutorial, we show you how to use DOM XML parser to create a XML file.

DOM Parser Example

At the end of the example, following XML file named “file.xml” will be created.

<!--?xml version="1.0" encoding="UTF-8" standalone="no" ?> 

		yong
		mook kim
		mkyong
		100000

File : WriteXMLFile.java – Java class to create a XML file.

package com.mkyong.core;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class WriteXMLFile {

	public static void main(String argv[]) {

	  try {

		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

		// root elements
		Document doc = docBuilder.newDocument();
		Element rootElement = doc.createElement("company");
		doc.appendChild(rootElement);

		// staff elements
		Element staff = doc.createElement("Staff");
		rootElement.appendChild(staff);

		// set attribute to staff element
		Attr attr = doc.createAttribute("id");
		attr.setValue("1");
		staff.setAttributeNode(attr);

		// shorten way
		// staff.setAttribute("id", "1");

		// firstname elements
		Element firstname = doc.createElement("firstname");
		firstname.appendChild(doc.createTextNode("yong"));
		staff.appendChild(firstname);

		// lastname elements
		Element lastname = doc.createElement("lastname");
		lastname.appendChild(doc.createTextNode("mook kim"));
		staff.appendChild(lastname);

		// nickname elements
		Element nickname = doc.createElement("nickname");
		nickname.appendChild(doc.createTextNode("mkyong"));
		staff.appendChild(nickname);

		// salary elements
		Element salary = doc.createElement("salary");
		salary.appendChild(doc.createTextNode("100000"));
		staff.appendChild(salary);

		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File("C:\\file.xml"));

		// Output to console for testing
		// StreamResult result = new StreamResult(System.out);

		transformer.transform(source, result);

		System.out.println("File saved!");

	  } catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	  } catch (TransformerException tfe) {
		tfe.printStackTrace();
	  }
	}
}

A new XML file is created in “C:\\file.xml“, with default UTF-8 encoded.

Note
For debugging, you can change the StreamResultto output the XML content to your console.

StreamResult result =  new StreamResult(System.out);
transformer.transform(source, result);
Advertisements
Comments
  1. Jimmy Hettinga says:

    You have noted very interesting details! ps nice internet site.

    Like

  2. e-tupakka 510 says:

    I always was concerned in this topic and still am, regards for posting.

    Like

  3. certified nurse assistant says:

    I think other web-site proprietors should take this site as an model, very clean and great user friendly style and design, as well as the content. You are an expert in this topic!

    Like

  4. music licensing organizations says:

    Very interesting details you have noted , appreciate it for putting up. “Women have been trained to speak softly and carry a lipstick. Those days are over.” by Bella Abzug.

    Like

  5. teething and fever says:

    Very interesting points you have observed , thanks for posting . “You bluffed me I don’t like it when people bluff me. It makes me question my perception of reality.” by Andrew Schneider.

    Like

  6. Parker Valle says:

    I have recently started a web site, the info you offer on this site has helped me greatly. Thanks for all of your time & work.

    Like

  7. broadjam scam says:

    You have remarked very interesting details ! ps nice site. “To grow mature is to separate more distinctly, to connect more closely.” by Hugo Von Hofmannsthal.

    Like

  8. Scrapebox forum says:

    You will find various agencies which deals with evidences located at a crime scene. Police use it for investigation, prosecuting attorney presents it before court of law as effectively as a forensic science technician analyzes evidences thoroughly to assist other agencies in criminal procedure. A forensic science technician conducts comprehensive chemical and physical study of evidence submitted by a law enforcement agency

    Like

  9. Scrapebox says:

    I went over this internet site and I think you have a lot of fantastic information, saved to fav (:.

    Like

  10. long travel tacoma says:

    Heya just wanted to give you a brief heads up and let you know a few of the images aren’t loading properly. I’m not sure why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same results.

    Like

  11. cheap vacations says:

    I have been exploring for a little for any high quality articles or weblog posts in this sort of house . Exploring in Yahoo I finally stumbled upon this website. Reading this info So i’m satisfied to exhibit that I have a very good uncanny feeling I came upon just what I needed. I such a lot unquestionably will make certain to don’t fail to remember this website and give it a glance on a relentless basis.

    Like

  12. hybrid car rental says:

    Absolutely composed articles, Really enjoyed reading through.

    Like

  13. kia motors philippines says:

    I’m really loving the theme/design of your blog. Do you ever run into any web browser compatibility issues? A few of my blog audience have complained about my site not working correctly in Explorer but looks great in Chrome. Do you have any recommendations to help fix this issue?

    Like

  14. kore dizileri izle says:

    Hello admin good post significantly thanks beloved this blog genuinely much

    Like

  15. Robert Scelfo says:

    I view something really special in this website.

    Like

  16. sanovnik trudnoca says:

    I’m uncertain where you’re getting the info, however very good topic.

    Like

  17. fireplace flame coloring says:

    First of all I would like to say extremely good blog! I got a short question that will I’d like to find out if you don’t mind. I’m curious to discover how you center your mind and clear your head right before writing. I’ve had a tough time clearing my head to get my ideas out. I really do get pleasure from writing but it really just seems like the initial 8 to 10 minutes are usually spent just trying to figure out where to begin. Any recommendations or simply hints? Kind regards!

    Like

  18. god strong tv says:

    Hey just wanted to give you a quick heads up. The text in your post seem to be running off the screen in Chrome. I’m not sure if this is a formatting issue or something to do with internet browser compatibility but I thought I’d post to let you know. The design and style look great though! Hope you get the issue resolved soon. Cheers

    Like

  19. four micro onde says:

    Someone essentially help to make significantly articles I’d state. That is the first time I frequented your website page and up to now? I amazed with the research you made to create this actual publish extraordinary. Magnificent activity!

    Like

  20. eliminating credit card bills says:

    wonderful points altogether, you simply gained a logo new reader. What would you recommend in regards to your submit that you made a few days ago? Any positive?

    Like

  21. Wesley says:

    I think you have noted some very interesting details , thanks for the post.

    Like

  22. Escort girl Paris says:

    I like this weblog it’s a master piece! Glad I noticed this on google.

    Like

  23. BAcklinks RSS Feeds says:

    I like this post, enjoyed this one regards for posting .

    Like

  24. computer mouses says:

    Just keep making good content. What precisely I wanted! I am browsing the major search engines the entire day to get a decent article this way

    Like

  25. cuckold says:

    Thanks for some other informative blog. Where else may just I am getting that kind of information written in such an ideal approach? I’ve a venture that I’m just now working on, and I’ve been at the look out for such info.

    Like

  26. Sheilah says:

    I’ve recently started a blog, the information you offer on this website has helped me greatly. Thanks for all of your time & work.

    Like

  27. coach credit card holder says:

    There is visibly a lot to know about this. I think you made some nice points in features also.

    Like

  28. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment. Is there any way you can remove me from that service? Thanks a lot!

    Like

  29. Juice Recipes says:

    A juice cleanse can be a very beneficial way to purify your body of the toxins building up there. Every day we are exposed to toxins in the air we breathe and the processed foods we eat.

    Like

  30. Clinton Turko says:

    Hi there I am so glad I found your website, I really found you by error, while I was researching on Aol for something else, Regardless I am here now and would just like to say thanks for a marvelous post and a all round interesting blog (I also love the theme/design), I don’t have time to read through it all at the moment but I have book-marked it and also added in your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the awesome job.

    Like

  31. Lynsey Everet says:

    Woah! I’m really loving the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between user friendliness and visual appeal. I must say you’ve done a amazing job with this. Additionally, the blog loads very fast for me on Chrome. Exceptional Blog!

    Like

  32. Aurelio Kot says:

    Do you mind if I quote a few of your articles as long as I provide credit and sources back to your site? My blog is in the very same area of interest as yours and my visitors would definitely benefit from a lot of the information you provide here. Please let me know if this okay with you. Thanks!

    Like

  33. carpet cleaning Northern Virginia says:

    You already know thus considerably on the subject of this subject, produced me personally consider it from so many various angles. Its like women and men aren’t involved unless it is something to accomplish with Lady gaga! Your personal stuffs nice. At all times deal with it up!

    Like

  34. alasda asdam says:

    wow! many thanks for that incredible document. I really liked it towards core. Hope you keep submitting like impressive content article

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s