gpt4 book ai didi

java - 为什么我的 scala 程序不忽略 xml 文件的 DTD?

转载 作者:行者123 更新时间:2023-11-30 03:18:53 25 4
gpt4 key购买 nike

我有一个包含以下代码的 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:

Ignore DTD specification in scala

Turn off DTD validation for scala.xml.XML

最佳答案

这对我有用:

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)

关于java - 为什么我的 scala 程序不忽略 xml 文件的 DTD?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31841399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com