Reterive XMl Data Using Java

I am very new to Java and Xml Parsing.My requirment is take xml file and store the XMl File data in database in the Table and columns format using java . I tried in google to get the right solution for it.but i am helpless.Till now what i did is , I can get the xml data dynamically and store either tag names or values. but my req is to take tag names only once as column names and data related to particular column in the row format can any one please correct my code .\[code\]<?xml version="1.0"?><company> <staff> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary> </staff> <staff> <firstname>low</firstname> <lastname>yin fong</lastname> <nickname>fong fong</nickname> <salary>200000</salary> </staff></company>\[/code\]Java Code\[code\] import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; public class XmlData{ static public void main(String[] arg){ try { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter XML File Path: "); String xmlFile = bf.readLine(); //Store the String into the File File file = new File(xmlFile); if(file.exists()){ // Create a factory DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); // Use the factory to create a builder DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(xmlFile); Element docEle = doc.getDocumentElement(); System.out.println("Root element of the document: "+ docEle.getNodeName()); // Get a list of all elements in the document NodeList list = doc.getElementsByTagName("*"); int totalElements = list.getLength(); System.out.println("XML Elements: " + totalElements); for (int i=0; i<list.getLength(); i++) { // Get element Element element = (Element)list.item(i); String tag=element.getTagName(); String name=list.item(0).getChildNodes().item(0).getNodeValue(); System.out.println(name); System.out.print(tag); System.out.print(" "); //System.out.println(element.getNodeName()); } } else{ System.out.print("File not found!"); } } catch (Exception e) { System.exit(1); } } }\[/code\]Output for this code:\[code\]company staff firstname lastname nickname salary staff firstname lastname nickname salary \[/code\]Expected Output:\[code\]FirstName, Lastname, nickname , salary //columnyong ,mook kim, mkyong , 100000 // rowslow ,yin fong, fong fong ,200000\[/code\]
 
Back
Top