我正在尝试解析HTML表的内容并将其写入CSV。我正在尝试Stax解析器HTML包含&nbps'
和&
我正在使用 org.apache.commons.lang3.StringEscapeUtils
逐行使用html线并写入新文件。
stax仍然无法解析未设计的字符。
请帮助我修复或处理此例外。
i测试以下XML片段 - <root><element>A B </element></root>
我将以下代码称为unescape html-
StringEscapeUtils.unescapeHtml4(escapedHtml)
并将其写入文件。
然后,我尝试使用Stax解析器 - 来解析该文件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)
它无法解析
的未排放值请帮助。
fileReader和文件作者是旧的实用程序类,不幸的是使用当前平台编码。在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在错误的多字节序列上跌跌撞撞。
使用standardcharset而不是字符串" UTF-8"取消
- 可以处理的无基本化语言Exception,
- 魔术常数。
保证支持标准柜。