2012-07-04 5 views
1

저는 Java와 Xml 구문 분석을 처음 사용합니다. 내 요구 사항은 xml 파일을 가져 와서 XML 파일의 데이터를 테이블과 컬럼 형식의 데이터베이스에 java를 사용하여 저장하는 것이다. 나는 그것을 위해 올바른 해결책을 얻기 위해 구글에서 노력했다. 그러나 나는 무기력하다. 지금까지 내가 한 일은 xml 데이터를 동적으로 가져 와서 태그 이름이나 값을 저장할 수 있습니다. 하지만 내 req는 열 이름과 행 형식의 특정 열에 관련된 데이터로 누구나 내 코드를 수정하십시오 태그 이름을 한 번만 사용하는 것입니다. 이 코드에 대한Java를 사용하여 XMl 데이터 가져 오기

<?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> 

자바 코드

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); 
    } 
    } 
    } 

출력 :

company 
staff 
firstname 
lastname 
nickname 
salary 
staff 
firstname 
lastname 
nickname 
salary 

예상 출력 : 난 당신이 이미와 데이터베이스 테이블을 만든 있으리라 믿고있어

FirstName, Lastname, nickname , salary //column 

yong  ,mook kim, mkyong  , 100000 // rows 
low  ,yin fong, fong fong ,200000 

답변

3

네 개의 열 - FirstNAme, LastName, 닉네임, 급여.

데이터를 읽고 DB에 저장하는 것이 정말 간단합니다.

import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 
import org.w3c.dom.Document; 
import org.w3c.dom.Element; 
import org.w3c.dom.NodeList; 

public class ParseStaff { 
    public static void main(String [] args){ 
     parseFile(); 
    } 
    public static void parseFile() { 
     //get the factory 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     try { 
      //Using factory get an instance of document builder 
      DocumentBuilder db = dbf.newDocumentBuilder(); 
      //parse using builder to get DOM representation of the XML file 
      //Document dom = db.parse("employees.xml"); 
      Document dom = db.parse("C:\\GAE\\NetBeansProjects\\Test\\src\\statff.xml"); 
      //get the root element 
      Element docEle = dom.getDocumentElement(); 
      //get a nodelist of elements 
      NodeList nl = docEle.getElementsByTagName("staff"); 

      if (nl != null && nl.getLength() > 0) { 
       for (int i = 0; i < nl.getLength(); i++) { 
        //get the employee element 
        Element el = (Element) nl.item(i); 
        String firstname = getTextValue(el, "firstname"); 
        String lastname = getTextValue(el, "lastname"); 
        String nickname = getTextValue(el, "nickname"); 
        int salary = getIntValue(el, "salary"); 

        System.out.println(firstname); 
        System.out.println(lastname); 
        System.out.println(nickname); 
        System.out.println(salary); 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 
    private static String getTextValue(Element ele, String tagName) { 
     String textVal = null; 
     NodeList nl = ele.getElementsByTagName(tagName); 
     if (nl != null && nl.getLength() > 0) { 
      Element el = (Element) nl.item(0); 
      textVal = el.getFirstChild().getNodeValue(); 
     } 

     return textVal; 
    } 
    private static int getIntValue(Element ele, String tagName) { 
     return Integer.parseInt(getTextValue(ele, tagName)); 
    } 
} 

인쇄됩니다 :

yong 
mook kim 
mkyong 
100000 
low 
yin fong 
fong fong 
200000 
+0

1 @sreehari을 : 실제로 getTextValue 도우미 방법은 매우 중요합니다! 하지만이 매우 일반적인 필요성을 달성하는 데 필요한 복잡성 때문에 정말 직설적이라고 말하면 안됩니다. XD – helios

+0

안녕하세요, 저는 원하는 것이 아닙니다. 역동적으로 저는 열 이름을 만들 필요가 있습니다. 행 형식 – Navyah

관련 문제