我已经从PDF中提取了以下字符串格式的数据。(请注意间距不均和换行符)。
Virtual Salary 25,100.00 EIS EE Contr. 7.90
Virtual Car Allowance 1,600.00 EPF Employee Contr. 2,937.00
Payment Received(Oversea) 4,265.01 SOCSO Employee Contr. 19.75
如何将字符串转换为XML,如下所示。
public void testMethod()
{
String extractedTestFromPDF=
" Virtual Salary 25,100.00 EIS EE Contr. 7.90\n"+
"\t Virtual Car Allowance 1,600.00 EPF Employee Contr. 2,937.00\n"+
" Payment Received(Oversea) 4,265.01 SOCSO Employee Contr. 19.75\n";
}
所需XML:
<xml>
<Data>
<Allowance>Virtual Salary</Allowance>
<Allowance_Amount>25,100.00</Allowance_Amount>
</Data>
<Data>
<Allowance>EIS EE Contr.</Allowance>
<Allowance_Amount>7.90</Allowance_Amount>
</Data>
<Data>
<Allowance>Virtual Car Allowance</Allowance>
<Allowance_Amount>1,600.00</Allowance_Amount>
</Data>
...
</xml>
答案 0 :(得分:0)
String fixedSizetoXML(String extractedTestFromPDF) {
String[] lines = extractedTestFromPDF.split("\\R");
Pattern pattern = Pattern.compile("^\\s*(\\S.{20})\\s\\s+([-\\d,\\.]+)\\s+.*$");
// (--------) (-----------)
return "<?xml verion="1.0">\n<Xml>\n"
+ Stream.of(lines)
.map(pattern::matcher)
.filter(m::find)
.map(m -> String.format("<Data>\n"
+ " <Allowance>%s</Allowance>\n"
+ " <Allowance_Amount>%s</Allowance_Amount>"
+ "</Data>,
m.group(1).trim(), m.group(2)))
.collect(Collectors.joining(""))
+ "<Xml>\n";
}
我随意添加了XML预处理指令<?xml ...>
,为清楚起见,将xml
更改为Xml
。
这些是具有固定长度字段的记录。盘点并不完全安全,
看到制表符\t
并考虑特殊字符:é
可以是一个字符,也可以是e
加上特殊的零宽度´
,我改用了正则表达式模式。金额前至少需要两个空白字符。
Java 7
String fixedSizetoXML(String extractedTestFromPDF) {
String[] lines = extractedTestFromPDF.split("\\R");
Pattern pattern = Pattern.compile("^\\s*(\\S.{20})\\s\\s+([-\\d,\\.]+)\\s+.*$");
// (--------) (-----------)
StringBuilder sb = new StringBuilder(lines.length * 64);
sb.append("<?xml verion="1.0">\n<Xml>\n");
for (String line : lines) {
Matcher m = pattern.matcher(line);
if (m.find()) {
String data = String.format("<Data>\n"
+ " <Allowance>%s</Allowance>\n"
+ " <Allowance_Amount>%s</Allowance_Amount>"
+ "</Data>,
m.group(1).trim(), m.group(2));
sb.append(data);
}
}
sb.append("<Xml>\n");
return sb.toString();
}