您所指的属性确实需要一个 EscapingWriterFactory 类。这是文档:
如果需要对属性值内容进行自定义输出转义,可以设置的属性。值集必须是类型 逃离WriterFactory。设置后,工厂将用于创建 每个写入器实例用于转义所有写入的属性值,两者 通过显式 XMLStreamWriter.writeAttribute(java.lang.String, java.lang.String) 方法,以及通过复制方法 (XMLStreamWriter2.copyEventFromReader(org.codehaus.stax2.XMLStreamReader2, 布尔值))。 [1]
关于如何实现“个人”逃避该工厂的实施的问题就可以完成这项工作。这是一个使用给定编写器的简单实现(受 [2] 启发),无需应用任何转义 - 这可能是您想要解决的任何特殊用例的起点:
class CustomXmlEscapingWriterFactory extends EscapingWriterFactory{
override def createEscapingWriterFor(writer: Writer, s: String): Writer =
new Writer(){
override def write(cbuf: Array[Char], off: Int, len: Int): Unit =
writer.write(cbuf, off, len)
override def flush(): Unit = writer.flush()
override def close(): Unit = writer.close()
}
override def createEscapingWriterFor(outputStream: OutputStream, s: String): Writer =
throw IllegalArgumentException("not supported")
}
class TestStreamXML extends AnyFunSuite{
val file = new File("stax2test.xml")
val fileOutputStream = new FileOutputStream(file)
val oprovider: OutputFactoryProviderImpl = new OutputFactoryProviderImpl()
val outputFactory: XMLOutputFactory2 = oprovider.createOutputFactory()
// your factory implementation goes here as property
outputFactory.setProperty(XMLOutputFactory2.P_ATTR_VALUE_ESCAPER, CustomXmlEscapingWriterFactory())
val writer= outputFactory.createXMLStreamWriter(fileOutputStream)
writer.writeStartDocument()
writer.writeStartElement("elem1")
writer.writeAttribute("att1", "This 
 That")
writer.writeEndElement()
writer.writeEndDocument()
}
结果输出如下所示:
<?xml version='1.0' encoding='UTF-8'?><elem1 att1="This 
 That"/>