在 groovy 中验证 xml 文档

validating a xml doc in groovy

我在 Groovy 中有一个 xml 对象..当我到达它时已经解析了它

def doc = new XmlSlurper().parse('sample.xml')

我想根据 XSD

验证它

然而,在示例代码中,这涉及 xml 以字符串或文件形式呈现

def xsdLocation = 'defn.xsd'
SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI)
   .newSchema( new File(xsdLocation))
   .newValidator()
   .validate(  doc  )

我无法弄清楚我需要将我拥有的(XmlSlurper.parse 的结果)传递给 validate()

的 StreamSource 类型对象的什么转换或组合

这对我有用。

import groovy.xml.XmlUtil

def doc = new XmlSlurper().parse('sample.xml') 

def xsdLocation = 'defn.xsd'

SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI)
   .newSchema( new File(xsdLocation))
   .newValidator()
   .validate(new StreamSource(new StringReader( XmlUtil.serialize(doc))))