让我们创建一个具有两个属性值的 XML 文件,其中包含一个扩展的 unicode 字符
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ERROR_XML), "UTF-8"))) {
XMLStreamWriter xmlStreamWriter = outputFactory.createXMLStreamWriter(writer);
xmlStreamWriter.writeStartDocument();
xmlStreamWriter.writeCharacters("\n");
xmlStreamWriter.writeStartElement("start");
xmlStreamWriter.writeAttribute("test1", "11");
xmlStreamWriter.writeAttribute("test2", "22");
xmlStreamWriter.writeEndElement();
xmlStreamWriter.writeEndDocument();
}
生成的文件如下所示:
<?xml version="1.0" ?>
<start test1="11" test2="22"></start>
如果再次读入并检查属性值
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(ERROR_XML), "UTF-8"))) {
XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader(reader);
xmlStreamReader.nextTag();
if (XMLStreamReader.START_ELEMENT == xmlStreamReader.getEventType() &&
"start".equals(xmlStreamReader.getLocalName()))
{
System.out.println(xmlStreamReader.getAttributeValue(0));
System.out.println(xmlStreamReader.getAttributeValue(1));
}}
这将打印
11
22
令人惊讶的是,第二个属性值包含 2 次扩展的 unicode 字符!
任何后续使用扩展字符作为属性值都会增加此计数。在一种情况下,我收到了包含 12000 个相同字符而不是一个的属性值。这里发生了什么?