Thursday, December 5, 2013

XML processing in Java

XML and HTML are Markup Languages. However, they are different. XML is generally used to store and transport structured data while HTML is used to format and present the data. Today XML is the most common tool for data transmissions on the web. In XML file, you can define your own tags or elements starting from a root tag and then its children tags. Here is an example of an XML file:

xml file example


The root element is Books. Under the root element, there are two sub-elements or children elements Book.

This tutorial is designed for people who come to work with XML file in Java. After completing the tutorial, you will be able to create an XML document and save it to a file, read data from an XML file, and modify elements in the XML file by using JDOM library. With the JDOM libary, XML file can be easily created, read, and modified.

Create XML document and Save it to a file

To create an XML document, first you will use the Element class to create a root element object. Then create a document object by using the Document class to wrap the root object. A child element object can also be constructed by using the Element class and added to root element by using the addContent method. You can add many children to the root element. To save the XML document to a file, you will use the XMLOutputter class. The XMLOutputter class has a method called output that can be used to write the document to the file.  See the example code below:

public static void createXML(){
//create a root element
Element root=new Element("Books");
//construct the document object with the root
Document doc=new Document(new Element("Books"));
//create first child element
Element b1=new Element("Book");
b1.setAttribute("Title","C++ for beginners");
b1.addContent(new Element("Author").setText("Dara"));
b1.addContent(new Element("Year").setText("2011"));
//add the first child to the root
root.addContent(b1);

//create second child element
Element b2=new Element("Book");
b2.setAttribute("Title","Java for programmers");
b2.addContent(new Element("Author").setText("Dara"));
b2.addContent(new Element("Year").setText("2012"));
//add the second child to the root
root.addContent(b2);
//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
try {
outputter.output(doc, new FileWriter("d:/books.xml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Read data from the XML file

Reading data from an XML file is a common task. This task can be accomplished easily by using JDOM. To read the data from the XML file, you will use SAXBuilder class to construct a document object from the XML file. After you have the document object, you can easily navigate through the document to access all its elements. Read the example code below:


public static void readXML(){
SAXBuilder builder=new SAXBuilder();
try {
//construct document object from the file books.xml
Document doc = (Document)builder.build(new File("d:/books.xml"));
//get the root element
Element root=doc.getRootElement();
//get all children of the root
List<Element> chs=root.getChildren();
for(Element e: chs){
System.out.println("Book:");
System.out.println("\t"+e.getChild("Author").getText());
System.out.println("\t"+e.getChild("Year").getText());
}

} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Modify the data in the XML file

Before you can modify the data in the XML file, first you need to read the XML file in to a document object as you did in the previous section. Then you can add new children elements to the root, update data of an element, or delete an element from the document. After you complete the tasks, call the output method of the XMLOutputter class to save change to the file. Here is the example code.

public static void ModifyXML(){
SAXBuilder builder=new SAXBuilder();
try {
Document doc = (Document)builder.build(new File("d:/books.xml"));
Element root=doc.getRootElement();
//create third child element
Element b3=new Element("Book");
b3.setAttribute("Title","C# for beginners");
b3.addContent(new Element("Author").setText("Dara"));
b3.addContent(new Element("Year").setText("2013"));

//add the third child to the root
root.addContent(b3);

//Update the year of a book
List<Element> chs=root.getChildren();
for(Element e: chs){
Element ce=e.getChild("Year");
if(ce.getText().equals("2013")){
ce.setText("2010");
break;
}
}
//Remove a book that has the title "C# for beginners"
for(Element e: chs){
if(e.getAttribute("Title").getValue().endsWith("C# for beginners")){
root.removeContent(e);
break;
}

}

//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(doc, new FileWriter("d:/books.xml"));

} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

compass app flashLight app

24 comments:

  1. Question:
    - How different between Class and Method ?
    - How different between using XML and other DBMS software like SqlServer, Oracle, Mysql ?

    ReplyDelete
  2. A METHOD is a member of a class. Xml is a language that can be used to write structured data to xml file. It is a common file for transmission on the web.

    ReplyDelete
  3. It has been 3 years since this post was written and it still feels like XML is a big part of java processing. custom essay writing service interns are currently learning the some basic java codes which they use on their daily task.

    ReplyDelete
  4. Alongside solid suite of center APIs, you have to know the correct linguistic structure and component of coding in Java to wind up distinctly fruitful Java Developer. java

    ReplyDelete
  5. JAXP is also possible way to process XML it's native API so it's give batter performance then JDOM

    ReplyDelete
  6. Really amazing post https://write-my-essay.cheap/cheapwritingservice-org-review/ you always post different article that very important and helpful in our daily routine matter. So I suggest to every visitor who read this post they must read this because they tells us about yoga who lose the weight.

    ReplyDelete
  7. nice article in your blog.thank you for sharing useful info.
    visit
    web programming tutorial
    welookups

    ReplyDelete
  8. This A Good Way To Appreciate The Teacher As They Put Their Efforts To Train Students. UK Dissertation Writers Appreciates The Teachers.

    ReplyDelete
  9. Science Channel’s Are Giving A Complete Knowledge To Its Viewers About Every Thing Students Write Done Dissertation On This Subjects And Show Its Importance.

    ReplyDelete
  10. Ahh that is great thank you ! Good for special needs too !

    ReplyDelete
  11. I like the valuable information you provide in your articles. I’ll bookmark your wepost and check again here regularly. I'm quite certain I will learn lots of new stuff right here! Good luck for the next! best web design software

    ReplyDelete
  12. I was doing a research for which I visited many marketing websites. And noticed that almost every website has the same pattern. I don’t know if it is a good thing or a bad thing, but it was interesting to know.

    ReplyDelete
  13. Recently, I read an online article about free trials weight loss pills. There were mixed opinions about the pills by the writer. She was confusing some positive points with the side effects of the pills. is forskolin good for weight loss Recently, I read an online article about free trials weight loss pills. There were mixed opinions about the pills by the writer. She was confusing some positive points with the side effects of the pills.

    ReplyDelete
  14. Finally I received my order, and I have been waiting for it for so long. There is free product samples mail with my order. But I am terrified to try those free products on my skin, as it is very much sensitive. iphone 7 vs iphone 7s Absolutely pent articles , Really enjoyed reading .

    ReplyDelete
  15. Whenever people spent an amount of money on online shopping, they usually get free stuff online. But this has never happened with me, and I tend to spent a certain amount. But I am never able to do that. testosterone supplements side effects Outstanding post, I conceive website owners should learn a lot from this blog its real user pleasant.

    ReplyDelete
  16. I think, billions of people over the globe breath in the dirtied air which is causing of various disorders like flu and some unique infections. This really is http://www.ukraineoutsourcingrates.com/app-development-ukraine-rates/ most exceedingly horrendous news for the next decade since, producing plants are leaving very dangerous smoke each day and influencing the air.

    ReplyDelete
  17. I liked up to you will obtain performed proper here. The comic strip is tasteful, your authored material stylish. however, you command get bought an edginess over that you wish be delivering the following. in poor health for sure come more formerly again as exactly the similar just about a lot continuously within case you protect this increase.
    web design company singapore

    ReplyDelete
  18. Appreciating the persistence you put into your blog and in depth information you present. It's great to come across a blog every once in a while that isn't the same out of date rehashed information. Excellent read! I've saved your site and I'm including your RSS feeds to my Google account.
    web design agency singapore

    ReplyDelete
  19. Please let me know if you're looking for a article writer for your site. You have some really good posts and I think I would be a good asset. If you ever want to take some of the load off, I'd love to write some articles for your blog in exchange for a link back to mine. Please shoot me an email if interested. Thanks!
    MediaOne guide on marketing

    ReplyDelete
  20. Pretty section of content. I just stumbled upon your web site and in accession capital to claim that I acquire in fact enjoyed account your weblog posts. Anyway I’ll be subscribing in your feeds or even I success you get right of entry to constantly quickly.
    domain name registration singapore

    ReplyDelete
  21. Im grateful for the blog post.Really thank you!
    โปรโมชั่นGclub ของทางทีมงานตอนนี้แจกฟรีโบนัส 50%
    เพียงแค่คุณสมัคร Gclub กับทางทีมงานของเราเพียงเท่านั้นร่วมมาเป็นส่วนหนึ่งกับเว็บไซต์คาสิโนออนไลน์ของเราได้เลยค่ะ
    สมัครสล็อตออนไลน์ >>> goldenslot
    สนใจร่วมลงทุนกับเรา สมัครเอเย่น Gclub คลิ๊กได้เลย

    ReplyDelete
  22. Jawa is a language of programming which is essential in computer language programming
    Dissertation Help UK

    ReplyDelete
  23. Currently it sounds like BlogEngine is the top blogging platform available right now. (from what I've read) Is that what you're using on your blog? List of Telecommunications Companies in Singapore

    ReplyDelete
  24. The removable drip tray collects all excess fat from your food and away from the surface of the electric cooktop, making it easy to clean up when you've finished preparing your meals.

    ReplyDelete