Turn off DTD validation for scala.xml.XML [duplicate]

99封情书 提交于 2020-01-05 18:53:32

问题


I want to load an XML document from an InputStream in Scala. Therefore I am using scala.xml.XML.load(is: InputStream): scala.xml.Elem.

The XML document is a SVG file that comes from Potrace and looks like this:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
 "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
 width="10.000000pt" height="10.000000pt" viewBox="0 0 10.000000 10.000000"
 preserveAspectRatio="xMidYMid meet">
<metadata>
Created by potrace 1.11, written by Peter Selinger 2001-2013
</metadata>
<g transform="translate(0.000000,10.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M14 73 c2 -10 11 -20 20 -21 13 -3 17 2 14 14 -4 25 -37 31 -34 7z"/>
<path d="M67 83 c-4 -3 -7 -15 -7 -25 0 -13 -7 -18 -26 -18 -14 0 -23 -4 -19
-10 17 -28 75 9 75 47 0 14 -12 17 -23 6z"/>
<path d="M74 21 c-5 -5 -22 -11 -39 -14 -27 -4 -27 -4 7 -6 20 0 40 4 43 10 9
14 1 21 -11 10z"/>
</g>
</svg>

My problem is, that parsing the InputStream takes around 15 seconds, which is annoying.

I figured out, that there's no delay when I remove the <!DOCTYPE> from the file. So probably the underlying SAXParser downloads the DTD in the <!DOCTYPE> to check that the document is valid.

How can I configure Scala's XML.load (probably by using XML.withSAXParser) to not validate the document?


回答1:


You need to disable validation using DTD for the parser that you use. Here is how: Ignore DTD specification in scala




回答2:


I found a solution on my own.

val factory = javax.xml.parsers.SAXParserFactory.newInstance()

// disable DTD validation
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 elem = scala.xml.XML.withSAXParser(factory.newSAXParser).load(inputStream)

This answer helped me in finding the solution.



来源:https://stackoverflow.com/questions/20936401/turn-off-dtd-validation-for-scala-xml-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!