0

当我将字符串解析为 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 &amp; Tear Parts Market, 2011–15</a>
4

1 回答 1

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();
...
于 2012-09-07T06:49:25.170 回答