我正在尝试使用 SAX 解析器解析这个 XML 文档:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE WIN_TPBOUND_MESSAGES SYSTEM "tpbound_messages_v1.dtd">
<WIN_TPBOUND_MESSAGES>
<SMSTOTP>
<SOURCE_ADDR>+447522579247</SOURCE_ADDR>
<TEXT>TEST: @£$¥èéùìò?ØøÅå& ^{}\\[~]¡€ÆæßÉ!\"#¤%'()*+,-./0123456789:;<=>? ÄÖÑܧ¿äöñüà end</TEXT>
<WINTRANSACTIONID>652193268</WINTRANSACTIONID>
</SMSTOTP>
</WIN_TPBOUND_MESSAGES>
解析<TEXT>
元素后,内容转换为:
TEST: @£$¥èéùìò?Ã�øÃ�Ã¥& ^{}\\[~]¡€Ã�æÃ�Ã�!\"#¤%'()*+,-./0123456789:;<=>? Ã�Ã�Ã�Ã�§¿äöñüà end
很明显,非 ASCII 字符发生了一些不好的事情。解析 XML 的代码如下所示:
public void parse(InputStream xmlStream) throws WinGatewayException {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
parser.setContentHandler(this);
parser.setErrorHandler(error);
parser.setEntityResolver(new DTDResolver());
parser.setDTDHandler(this);
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/validation/schema", true);
parser.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", true);
parser.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error", false);
parser.parse(new InputSource(xmlStream));
}
并且引用的对象this
具有以下方法:
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equals("TEXT")) {
logger.debug("Parsed message text: " + cData.toString());
message.setText(cData.toString());
}
}
为什么 XML 解析器不保留这些非 ASCII 字符?