Groovy XmlSlurper:内容不允许在XML文档的开头

5

我正在尝试解析一个XML文件,但遇到了这个错误:

org.xml.sax.SAXParseException: Content is not allowed in prolog

我看到了SO上的其他帖子,但我的XML文档看起来没问题——在XML声明之前没有额外的字符或空格。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE coverage SYSTEM "http://cobertura.sourceforge.net/xml/coverage-04.dtd">
<coverage branch-rate="0.24074074074074073" branches-covered="39" branches-valid="162" complexity="0" line-rate="0.3485915492957746" lines-covered="198" lines-valid="568" timestamp="1396622452625" version="0.2.6">

以下是脚本(Groovy 1.8.9)的相关部分:
def coveragedata = new XmlSlurper(false,false).parseText(coverageFile)

感谢您的帮助。
2个回答

8
你应该能够做到这一点:
def parser = new XmlSlurper() 
parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)
def coverageData = parser.parse( coverageFile )

如果coverageFile是一个包含文件中XML内容的字符串(如上文所述),则可以使用parseText而不是parse

parser.parseText( coverageFile )

我认为这通常应该可以工作,但是使用这个解决方案会导致连接超时错误。这必须在一个没有访问互联网的内部网络上运行,所以我想忽略 DOCTYPE。 - JamesE
@JimG 请尝试使用 new XmlSlurper(false, false) 作为构造函数。 - tim_yates

2

这段代码运行良好:

def coveragedata = new XmlSlurper(false,false,true).parseText(coverageFile)
println coveragedata.'@branch-rate'

这将适用于Groovy 2.x,但不适用于1.8.9。 - JamesE
另外,假设coverageFile是一个File,你需要使用parse而不是pareText - tim_yates
好的,在我的代码中,coverageFile 实际上是一个 String 变量的名称,但还是谢谢! - Opal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接