Why is my scala program not ignoring my xml file's DTD?

556 Views Asked by At

I have an XML file that contains the following code

   <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>

I have code that tries to ignore the DTD and add a node to the ClientConfig part of my file by reading in the file as a file input stream as follows:

   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)

However, despite adding all this the DTD does not end up getting ignored by the XML parser and ends up being expanded/resolved in the XML file. Why exactly is the DTD not being ignored?

I also want to add I followed these links to ignore my DTD:

Ignore DTD specification in scala

Turn off DTD validation for scala.xml.XML

1

There are 1 best solutions below

0
On BEST ANSWER

This worked for me:

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)