当我将字符串解析为org.w3c.dom.Element时,我遇到了异常。
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 245; Invalid byte 3 of 3-byte UTF-8 sequence.
我用来将字符串转换为元素的代码是:
public Element convertStringToDoc(String xmlString) throws Exception{
org.w3c.dom.Document doc;
try {
java.io.InputStream sbis = new java.io.StringBufferInputStream(xmlString);
javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
b.setNamespaceAware(false);
doc = null;
javax.xml.parsers.DocumentBuilder db = null;
db = b.newDocumentBuilder();
doc = db.parse(sbis);
org.w3c.dom.Element e = doc.getDocumentElement();
return e;
} catch (Exception e1) {
throw e1;
} }
我的输入字符串是:
<?xml version="1.0" encoding="UTF-8"?>
<a id="ctl00_RSContent1_ResultsList_ctl00_ProductTitleLink" href="../Product/the_western_european_wear_tear_parts_market_201115?productid=TD00033-006">The Western European Wear & Tear Parts Market, 2011–15</a>
答案 0 :(得分:1)
在我看来,java String类不是UTF-8编码的。似乎“ - ”序列在java字符串unicode中是UTF-8中不允许的字节编码。像这样改变你的代码......
...
byte[] utf8Bytes=xmlString.getBytes("UTF-8");
java.io.InputStream sbis = new java.io.ByteArrayInputStream(utf8Bytes);
javax.xml.parsers.DocumentBuilderFactory b = javax.xml.parsers.DocumentBuilderFactory.newInstance();
...