1

我有一个包含以下代码的 XML 文件

   <Root>
    <!DOCTYPE stylesheet [
<!ENTITY CLARK_HISTORICAL_ALLOCATION_CLASS "location.stuff.things">
<!ENTITY CLARK_UNIFORM_ALLOCATION_CLASS "location.stuff.items">
<!ENTITY CLARK_PSEUDO_UNIFORM_ALLOCATION_CLASS "location.items.stuff">
]>
     <ServerConfig>
       <host name="allen" env="flat"/>
     </ServerConfig>
     <ClientConfig>
       <host name="george" env="flat"/>
       <host name="alice" env="flat"/>
       <host name="bernice" env="flat"/>
    </ClientConfig>
   </Root>

我的代码试图忽略 DTD,并通过将文件作为文件输入流读入,将节点添加到文件的 ClientConfig 部分,如下所示:

   val factory = javax.xml.parsers.SAXParserFactory.newInstance()
    factory.setValidating(false)
    factory.setFeature("http://xml.org/sax/features/validation", false)
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false)
    factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
    factory.setFeature("http://xml.org/sax/features/external-general-entities", false)
    factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false)
    val data = scala.xml.XML.withSAXParser(factory.newSAXParser).load(FileInputstream)
    val p = new XMLPrettyPrinter
    val added = addNewEntry(data, "bob", "flat")

  def toBeAddedEntry(name: String, env: String) = <host name={ name } env={ env } />
  def addNewEntry(originalXML: Elem, name: String, env: String) = {
    originalXML match {
      case e @ Elem(_, _, _, _, configs @ _*) => {
        val changedNodes = configs.map {
          case <ClientConfig>{ innerConfigs @ _* }</ClientConfig> => {
            <ClientConfig> { toBeAddedEntry(name, env) ++ innerConfigs }</ClientConfig>
          }
          case other => other
        }
        e.copy(child = changedNodes)
      }
      case _ => originalXML
    }
  }
p.write(added)(System.out)

然而,尽管添加了所有这些,DTD 并没有最终被 XML 解析器忽略,而是最终在 XML 文件中展开/解析。为什么不忽略 DTD?

我还想补充一下,我按照这些链接忽略了我的 DTD:

忽略scala中的DTD规范

关闭 scala.xml.XML 的 DTD 验证

4

1 回答 1

2

这对我有用:

object MyXML extends XMLLoader[Elem] {
  override def parser: SAXParser = {
    val f = javax.xml.parsers.SAXParserFactory.newInstance()
    f.setValidating(false)
    f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
    f.newSAXParser()
  }
}

val data = MyXML.load(someXML)
于 2015-08-05T21:15:10.897 回答