我正在尝试解析HTML表格的内容并将其写入CSV。
我正在尝试StaX解析器
html包含转义字符,例如&nbps'
和&
我正在使用org.apache.commons.lang3.StringEscapeUtils
逐行使用html并写入新文件。
StAX仍然无法解析未转义的字符。
请帮我修复或处理此异常。
我测试下面的xml片段 -
<root><element>A B </element></root>
我将下面的代码称为unescape html -
StringEscapeUtils.unescapeHtml4(escapedHtml)
并将其写入文件。
然后我尝试使用Stax Parser解析该文件 -
public void unescapeHtmlFile(String filePath) throws IOException{
BufferedReader fileReader = null;
BufferedWriter fileWriter = null;
try{
fileReader = new BufferedReader(new FileReader(filePath));
fileWriter = new BufferedWriter(new FileWriter("./out/UnescapedHtml.html"));
String line = null;
String unescapedLine = null;
while((line=fileReader.readLine())!=null){
System.out.println("Before: " + line);
unescapedLine = StringEscapeUtils.unescapeHtml4(line);
System.out.println("After: " + unescapedLine);
fileWriter.newLine();
fileWriter.write(unescapedLine);
}
}finally{
fileReader.close();
fileWriter.close();
}
}
输出低于 -
Document started
<?xml version="null" encoding='UTF-8' standalone='no'?>
Element started
<root>
Element started
<element0>
Characters
0123456 7890 ABC DEF
Element ended
</element0>
Element started
<element1>
javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,66]
Message: Invalid byte 1 of 1-byte UTF-8 sequence.
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:596)
at com.sun.xml.internal.stream.XMLEventReaderImpl.nextEvent(XMLEventReaderImpl.java:83)
at parser.StreamParserTest.main(StreamParserTest.java:30)
javax.xml.stream.XMLStreamException: ParseError at [row,col]:[1,66]
Message: XML document structures must start and end within the same entity.
at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.next(XMLStreamReaderImpl.java:598)
at com.sun.xml.internal.stream.XMLEventReaderImpl.nextEvent(XMLEventReaderImpl.java:83)
at parser.StreamParserTest.main(StreamParserTest.java:30)
无法解析未转义的
值
请帮忙。
答案 0 :(得分:1)
类FileReader和FileWriter是旧的实用程序类,遗憾的是它们使用当前的平台编码。在Windows上几乎肯定不是UTF-8。而XML一般采用UTF-8(实际上可以代表所有字符。
fileReader = new BufferedReader(new FileReader(filePath));
fileWriter = new BufferedWriter(new FileWriter("./out/UnescapedHtml.html"));
应该是
fileReader = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath), StandardCharsets.UTF_8));
fileWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("./out/UnescapedHtml.html"),
StandardCharsets.UTF_8));
说实话,应该阅读<?xml ...?>
并查看它是否具有charset的encoding
属性,默认为UTF-8。这可以用StandardCharsets.ISO_8859_1
来完成,因为UTF-8会在错误的多字节序列上发现错误。
使用StandardCharsets代替字符串“UTF-8”取消
保证支持StandardCharsets。