使用 Stax2 转义 Scala 中的特殊字符

问题描述 投票:0回答:1
java scala stream streamwriter stax
1个回答
1
投票

您所指的属性确实需要一个 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 &#x0A; That"/>

[1] https://fasterxml.github.io/stax2-api/javadoc/4.0.0/org/codehaus/stax2/XMLOutputFactory2.html#P_ATTR_VALUE_ESCAPER

[2] 使用 jackson-dataformat-xml 转义引号

© www.soinside.com 2019 - 2024. All rights reserved.