【发布时间】:2014-08-08 02:08:05
【问题描述】:
我需要一些听起来很简单但给我带来麻烦的帮助。
我有一个文本文件 (record.txt),其中包含一个根元素“PatientRecord”和重复的子标签(“名字”、“年龄”、血型、地址等...)但具有不同的价值,因为它是每个人的记录。我只对将标签之间的值打印到每个人的新文本文件感兴趣,但只对我想要的元素感兴趣。例如,对于我上面提到的标签,我只需要姓名和年龄,而不需要该患者的其余信息。如何仅打印出用逗号分隔的值,然后转到下一位患者? 这是我到目前为止的代码
package patient.records;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class ProcessRecords {
private static final String FILE = "C:\\Users\\Desktop\\records.txt";
private static final String RECORD_START_TAG = "<PatientRecord>";
private static final String RECORD_END_TAG = "</PatientRecord>";
private static final String newFileName = "C:\\Users\\Desktop\\DataFolder\\";
public static void main(String[] args) throws Exception {
String scan;
FileReader file = new FileReader(FILE);
BufferedReader br = new BufferedReader(file);
Writer writer = null;
while ((scan = br.readLine()) != null)
{
if (scan.contains(RECORD_START_TAG)) {
//This is the logic I am missing that will only grab the element values
//between the tags inside of the file
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(newFileName + "Record Data" + ".txt"), "utf-8"));
}
else if (scan.contains(RECORD_END_TAG)) {
writer.close();
writer=null;
}
else {
// only write if writer is not null
if (writer!=null) {
writer.write(scan);
}
}
}
br.close();
}
} //This is the end of my code
我正在阅读的文本文件 (record.txt) 如下所示:
<PatientRecord> <---first patient record--->
<---XML Schema goes here--->
<Info>
<age>66</age>
<first_name>john</first_name>
<last_name>smith</last_name>
<mailing_address>200 main street</mailing_address>
<blood_type>AB</blood_type>
<phone_number>000-000-0000</phone_number>
</PatientRecord>
<PatientRecord> <---second patient record--->
<---XML Schema goes here--->
<Info>
<age>27</age>
<first_name>micheal</first_name>
<last_name>thompson</last_name>
<mailing_address>123 baker street</mailing_address>
<blood_type>O</blood_type>
<phone_number>111-222-3333</phone_number>
</PatientRecord>
所以理论上,如果我只想从这个文本文件中为所有患者打印出标签中的名字、邮寄地址和血型的值,它应该如下所示:
john, 200 main street, AB
//this line is blank
michael, 123 baker street, O
感谢您的任何帮助。如果您觉得我的代码应该修改,那么我完全赞成。谢谢。
【问题讨论】:
-
文本是这样混合内容还是被父标签包裹?