首页 > 代码库 > Invalid byte 1 of 1-byte UTF-8 sequence(XML读取异常)

Invalid byte 1 of 1-byte UTF-8 sequence(XML读取异常)

XML读取异常Invalid byte 1 of 1-byte UTF-8 sequence.

用xstream进行JavaBean与xml之间的转换,无法设定字符集编码格式,会导致上述异常。

解决方法:org.w3c.dom(java dom)解析xml文档,在此仅列出write方法:

 1 public static void write(String xmlFile, String encoding) 2             throws ParserConfigurationException, FileNotFoundException, 3             TransformerException, UnsupportedEncodingException { 4         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 5         DocumentBuilder builder = factory.newDocumentBuilder(); 6         Document document = builder.newDocument(); 7         Element root = document.createElement("sememewords"); 8         document.appendChild(root); 9 10         Element e = document.createElement("sememeword");11         e.setTextContent("java dom Test");12         root.appendChild(e);13 14         TransformerFactory tf = TransformerFactory.newInstance();15         Transformer transformer = tf.newTransformer();16         DOMSource source = new DOMSource(document);17         transformer.setOutputProperty(OutputKeys.ENCODING, "utf8");18         transformer.setOutputProperty(OutputKeys.INDENT, "yes");19         PrintWriter pw = new PrintWriter(20                 new BufferedWriter(new OutputStreamWriter(new FileOutputStream(21                         xmlFile), encoding)));22         StreamResult result = new StreamResult(pw);23         transformer.transform(source, result);24         pw.flush();25         pw.close();26     }