java - 使用 buffWrite 或 FileWriter 将 xml 文件拆分为多个文件
问题描述
我有一个 xml 文件,上面有不同类型的医疗数据。我正在尝试按标签名称或按行将 xml 文件拆分为多个文件。我从 csv 文件中获取此 xml 数据。xml 文件数据如下所示。
每个分割后的文件应命名为descriptor_pdx01.xml、descriptor_pdx02.xml、descriptor_pdx03.xml ......等。
我正在尝试使用 Buff Write 或 FileWriter 在 Java 中完成此操作。这是我为写入 xml 文件而编写的代码。问题是试图弄清楚如何使用 buffwrite 和 Filewriter 将 XML 文件拆分为 java 中的多个文件
这是 CSV 文件的内容:
TESTCLIENT_2017_09_30 pdx01 Carcinosarcoma C34448 M 12
TESTCLIENT_2017_09_30 pdx02 Esophageal carcinoma C4025
TESTCLIENT_2017_09_30 pdx03 Esophageal carcinoma C4025 45
TESTCLIENT_2017_09_30 pdx04 Carcinosarcoma C34448 F
TESTCLIENT_2017_09_30 pdx05 Esophageal carcinoma C4025 F 60
TESTCLIENT_2017_09_30 pdx06 Esophageal carcinoma C4025 F 66
TESTCLIENT_2017_09_30 pdx07 Carcinosarcoma C34448 M 70
public static void writeXmlFile(String[] headers, ArrayList <String> stringsFromCsv, String fileName){
try {
BufferedWriter buffWrite = new BufferedWriter(new FileWriter(fileName));
buffWrite.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
buffWrite.write("<patient>\r\n");
//String array that is the same size is that of the string from csv from line 66-69
//For each string in the csv file
for(String s:stringsFromCsv){
buffWrite.write("\t<person>\r\n");
//Split the line into an array of strings
String fields[] = s.split(",");
String[] stringToWrite = fields;
//Initiate a string variable and using the field array values form the xml and assign it to the string variable
//DO a method call and Send the string and fileName (descriptor_field[1])
//For each item in that array of strings
for(int i=0; i<fields.length; i++){
//Define a String and keep on adding to that string using field element array, String should be outside for loopLol
//Write the corresponding header to the file, as well as the value from the array 'fields'
buffWrite.write("\t\t<" + headers[i] +">"+ fields[i] + "</" + headers[i] +">\n");
}
buffWrite.write("\t</person>\n");
}
buffWrite.write("</people>");
buffWrite.close();
}
catch (IOException ioe){ System.err.println("Error while writing to xml file in writeXmlFile: "); ioe.printStackTrace();
}
}
如果您能提供有关如何执行此操作的任何指导,将不胜感激。
解决方案
正如一些人在您的问题中评论的那样,您的代码中有很多问题。
我会使用一个轻量级库将您的 CSV 和 XML 文件处理成 POJO。
我的建议?BeanIO是一个非常好的读/写 CSV 和 XML 文件的库。
编写您的 POJO 并使用 BeanIO@Record
和@Field
注释。BeanIO 将优雅地将 CSV / XML 解析为您的 POJO,因此您可以做任何您需要的事情。
推荐阅读
- python - 程序可以检测它是否是通过 shell 启动的吗?
- laravel - Laravel 身份验证记住我功能不起作用
- javascript - 有没有办法自动按下 Google App Script msgBox 上的 OK 按钮?
- sql - 加入一对多,返回最小大于结果
- gradle - 在 docker 容器中离线运行 Gradle 构建
- java - Retrofit 2.7.1 连接失败
- java - Firebase 在加载到嵌套对象时返回空数据快照
- c# - 自定义控件绑定设置器未触发
- javascript - 获取表格第二列的值,然后用 Javascript 绘制它
- javascript - 测试反应 redux 渲染返回未定义的组件