如何将xml文件转换为字符串并将其写入xml格式的另一个文件?

时间:2016-04-28 15:20:43

标签: java file-io xml-parsing

我有一个要求,我需要将xml文件转换为字符串,然后将其作为有效的xml格式写入另一个文件。

我尝试了很少的逻辑,但所有这些都无法将字符串写入xml文件格式,因为它始终作为XML标记而不是字符串。

例如我的代码是

<?xml version="1.0" encoding="UTF-8"?>
<Students>
    <Student_Name>Srinivas</Student_Name>
    <Student_FullName>Srinivas_Kumar</Student_FullName>
    <DOB>1992-09-25</DOB>
    <FlatNo>#04, 8th main</FlatNo>
    <Locality>Gandhi Road</Locality>
</Students>

预期输出应该像

<?xml version="1.0" encoding="UTF-8"?>
<ns0:message>
<Students><Student_Name>Srinivas</Student_Name><Student_FullName>Srinivas_Kumar</Student_FullName><DOB>1992-09-25</DOB><FlatNo>#04, 8th main</FlatNo><Locality>Gandhi Road</Locality></Students>
</ns0:message>

请帮助我。

我的一个逻辑是

public static void main(String[] args)throws IOException { 
    FileInputStream fin = new FileInputStream("path"); 
    FileOutputStream fout = new FileOutputStream("path"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(fin)); 
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fout)); 
    String initialtag = . 
    String endtag = . 
    String line ; 
    bw.write(initialtag); 
    while((line = br.readLine()) != null) { 
        line.replaceAll("<","&lt"); 
        line.replaceAll(">","&gt"); 
        bw.write(line); 
    } 
        bw.write(endtag); 
        bw.close(); 
}

0 个答案:

没有答案