2012-06-20 53 views
0

我正在通過XML解析器的代碼,我發現這個代碼, 但我想保存結果數據到一個文本文件。xml解析器數據到一個文本文件

public class ReadXMLFile 
{ 

public static void main(String argv[]) 
{ 

    try { 

    File fXmlFile = new File("test.xml"); 
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); 
    Document doc = dBuilder.parse(fXmlFile); 
    doc.getDocumentElement().normalize(); 

    System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); 
    NodeList nList = doc.getElementsByTagName("test"); 
    System.out.println("-----------------------"); 

    for (int temp = 0; temp < nList.getLength(); temp++) { 

     Node nNode = nList.item(temp); 
     if (nNode.getNodeType() == Node.ELEMENT_NODE) { 

      Element eElement = (Element) nNode; 

      System.out.println("ID : " + getTagValue("id", eElement)); 
      System.out.println("Name : " + getTagValue("Name", eElement)); 
      System.out.println("AGE: " + getTagValue("age", eElement)); 

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

private static String getTagValue(String sTag, Element eElement) 
{ 
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes(); 

    Node nValue = (Node) nlList.item(0); 

return nValue.getNodeValue(); 
} 

} 

如何將輸出保存到文本文件?

請建議我對此.......

+0

你有沒有寫過任何數據到文本文件? – Mark

回答

0

創建一個作家寫一個文件,並替換的System.out.println()與Writer.write()。

BufferedWriter writer = new BufferedWriter(new FileWriter(file)); 
writer.write(s); 
writer.newLine();