2014-02-27 39 views
0

實際上,我需要替換源xml中的一些標記並將這些文件編寫爲新文件。在這裏我的代碼工作正常,但現在我無法打開輸出XML。在輸出XML中,我有一些泰米爾語單詞。這是文件不能打開的原因無法使用java將文件從一個xml寫入另一個xml

public class dxml { 

    public static StringBuffer sb = new StringBuffer() ; 

public static void main(String [] args) throws Exception { 
    File xmlFile = new File("/home/dev702/Desktop/axl/Data Entry.xml"); 
    BufferedReader br = new BufferedReader(
       new FileReader("/home/dev702/Desktop/axl/Data Entry.xml")); 
    String line = null; 
    int linecount = 1; 
    FileWriter fw; 
    BufferedWriter bw = null; 
    fw = new FileWriter("/home/dev702/Desktop/axl/Data_Entry_OPT.xml") ; 
    bw = new BufferedWriter(fw); 
    while((line = br.readLine())!= null) 
     { 
      if(linecount > 2) 
      { 
       line = line.replaceAll("Data_x0020_Entry_x0020_Date", 
                   "DataEntryDate"); 
      //bw.write(line); 
      }  
     bw.write(line); 
     linecount++; 
     System.out.println(line); 
     } 
    bw.close(); 
    fw.close(); 
    } 
} 
+0

你得到的錯誤是什麼? –

+0

我沒有收到任何錯誤,但新文件沒有打開 – user3354849

+0

您正在使用哪種編輯器? –

回答

1

如果你想將XML轉換成另一種形式的XML,你應該使用XSLT來實現這一點。 Java支持轉換兩個文檔......下面是如何實現這一點的代碼片段。

這個前提的確是你將你的原始XML寫入一個文檔,設置XSLT使用並將其轉換爲另一個文檔。

使用XSLT的範圍在本答覆之外。我建議使用Altova出色的XMLSpy來測試您的XSLT。

public class Mapper { 


public Document convert(Document originalDocument, Resource xsltResource) throws TransformerException, ParserConfigurationException, 
     JAXBException, IOException, SAXException { 

    /** 
    * You'll need to create your documentBuilder to build the new document. 
    */ 
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); 
    documentBuilderFactory.setNamespaceAware(true); 
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); 

    /** 
    * Set up your transformer factory, you'll need to pass your XSLT file in as an inputstream 
    * I've passed it in here as a method arg and it's a Spring Resource but you can do it however you like. 
    */ 
    TransformerFactory transformerFactory = TransformerFactory.newInstance(); 
    Transformer transformer = transformerFactory 
      .newTransformer(new StreamSource(xsltResource.getInputStream())); 

    /** 
    * Set the encoding to avoid headaches. 
    */ 
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 


    /** 
    * Create a BAoS to hold your original document. 
    */ 
    ByteArrayOutputStream os = new ByteArrayOutputStream(); 
    transformer.transform(new DOMSource(originalDocument), new StreamResult(os)); 

    /** 
    * Do the transformation. 
    */ 
    return documentBuilder.parse(new InputSource(new StringReader(os.toString("UTF-8")))); 

    } 
} 
+0

爲此我可以得到輸入文件和輸出文件..你可以詳細說明 – user3354849

+0

嗨,所以在你的情況下,輸入文件是/ home/dev702/Desktop/axl/Data Entry.xml XSLT也是一個文件。您需要將您的XML文件轉換爲Document對象。谷歌可以幫助你做到這一點,你的XLST文件,你需要把它作爲一個InputStream。你的輸出(轉換後)將是一個Document對象,然後你可以寫出一個文件。 –

相關問題