2016-12-09 3 views
0

모든 XML 내용의 코드는 다음과 같습니다.XML의 내용을 CSV 파일로 저장

는 지금, 나는 beginig에 열려 스트림 라이터를 가지고,하지만 난 방법을 추가하는 방법을 모른다 :

public class ReadXML { 

    public static void main(String[] args) { 

    try { 

    File file = new File("C:\\test.xml"); 
    File outputFile = new File("C:\\test.csv"); 

    DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
    Document doc = dBuilder.parse(file); 
    BufferedWriter bw = null; 
    FileWriter fw = null; 

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 

    if (doc.hasChildNodes()) { 
     printNote(doc.getChildNodes()); 
    } 
    } catch (Exception e) { 
    System.out.println(e.getMessage()); 
    } 
    } 

    private static void printNote(NodeList nodeList) { 

    for (int count = 0; count < nodeList.getLength(); count++) { 

    Node tempNode = nodeList.item(count); 

    if (tempNode.getNodeType() == Node.ELEMENT_NODE) { 

     System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]"); 
     System.out.println("Node Value =" + tempNode.getTextContent()); 

     if (tempNode.hasAttributes()) { 

      // get attributes names and values 
      NamedNodeMap nodeMap = tempNode.getAttributes(); 

      for (int i = 0; i < nodeMap.getLength(); i++) { 
       Node node = nodeMap.item(i); 
       System.out.println("attr name : " + node.getNodeName()); 
       System.out.println("attr value : " + node.getNodeValue()); 
      } 
     } 
     if (tempNode.hasChildNodes()) { 
      // loop again if has child nodes 
      printNote(tempNode.getChildNodes()); 
     } 
     System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]"); 
    } } }} 

bw.write

ReadXML.java 너 나 좀 도와 줄 수있어? 문제를 해결하는 방법을 안다면 위대 할 것입니다.

감사합니다.

+0

"메소드에 추가"란 무엇을 의미합니까? CSV 파일에 어떤 데이터를 기록 하시겠습니까? 그리고 그건 그렇고, 당신의 작가는 열려 있지 않습니다. 그것은 null입니다. – Quagaar

+0

지금은 모든 데이터를 저장하고자하므로 tempNode.getTextContent()); bw에 추가해야합니다 – 4est

답변

1

그래, 정확히 무엇이 문제인지는 모르겠지만 이것이 도움이 될 수 있습니다.

첫째, 작가 엽니 다 printNote에 전달 그런

final BufferedWriter w = new BufferedWriter(new FileWriter(outputFile)); 

을 : 당신이 노드가있을 때

private static void printNote(final NodeList nodeList, final BufferedWriter w) throws IOException { 
    // ... 
} 

당신이 원하는에 :

printNote(doc.getChildNodes(), w); 

그에 따라 방법을 수정 파일에 쓰기 :

w.write(node.getTextContent()); 
w.newLine(); 

작업이 끝나면 작가를 닫는 것을 잊지 마십시오!

편집

작가 닫는 예 :

public static void mainv1(String[] args) { 

    File file = new File("C:\\test.xml"); 
    File outputFile = new File("C:\\test.csv"); 

    BufferedWriter bw = null; 

    try { 
     DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
     Document doc = dBuilder.parse(file); 

     System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 

     // Open in try because FileWriter constructor throws IOException 
     bw = new BufferedWriter(new FileWriter(outputFile)); 

     if (doc.hasChildNodes()) { 
      printNote(doc.getChildNodes(), bw); 
     } 
    } catch (Exception e) { 
     System.out.println(e.getMessage()); 
    } finally { 
     // Check for null because bw won't be initialized if document parsing failed 
     if (bw != null) { 
      try { 
       bw.close(); 
      } catch (final IOException e) { 
       // Log error 
      } 
     } 
    } 
} 
  • Java7

    1. 오래된 학교를 높은

      public static void main(String[] args) { 
      
          File file = new File("C:\\test.xml"); 
          File outputFile = new File("C:\\test.csv"); 
      
          // Since Java7 you can use try-with-resources 
          // The finally block closing the writer will be created automatically 
          try (BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) { 
      
           DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
           Document doc = dBuilder.parse(file); 
      
           System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 
      
           if (doc.hasChildNodes()) { 
            printNote(doc.getChildNodes(), bw); 
           } 
          } catch (Exception e) { 
           System.out.println(e.getMessage()); 
          } 
      } 
      
  • +0

    감사합니다! 닫기가 주 방법이되어야합니까? – 4est