代码之家  ›  专栏  ›  技术社区  ›  Denis Sablukov

是否有用于验证XML的gradle插件?

  •  0
  • Denis Sablukov  · 技术社区  · 7 年前

    我在一个项目中工作,我们有xml文件用于代码生成,我们使用 gradle

    格拉德尔 plugins 这可能有助于日常任务,我想知道是否有一些用于xml简单验证的插件(缺少引号和括号)。

    我想得到的文件名和遗漏的结果清单。

    UPD如果在不久的将来需要对xml文件(标记、参数)进行完全验证,我应该怎么做?

    1 回复  |  直到 7 年前
        1
  •  1
  •   lance-java    7 年前

    写自己的很简单

    class XmlValidate extends DefaultTask {
        @InputFiles
        private FileCollection xmlFiles
    
        @InputFile
        File xsd
    
        void xml(Object files) {
           FileCollection fc = project.files(files)
           this.xmlFiles = this.xmlFiles == null ?  fc : this.xmlFiles.add(fc)
        }
    
        @TaskAction
        public void validateXml() {
            DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            Validator validator = null
            if (xsd != null) {
                SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
                Schema schema = factory.newSchema(new StreamSource(xsd))
                validator = schema.newValidator()
            } 
            Set<File> failures = [] as Set
            xmlFiles.forEach {
                Document document = null
                try {
                    document = parser.parse(it)
                } catch (Exception e) {
                    logger.error("Error parsing $it", e) 
                    failures << it
                } 
                if (document && validator) {
                    try {
                        validator.validate(new DOMSource(document))
                    } catch (Exception e) {
                        logger.error("Error validating $it", e) 
                        failures << it
                    } 
                } 
            }
            if (failures) throw new BuildException("xml validation failures $failures") 
        } 
    }
    

    build.gradle中的用法

    task validateXml(type: XmlValidate) {
        xml ['foo.xml', 'bar.xml']
        xml fileTree(dir: 'src/main/resources/baz', include: '*.xml')
        xsd = file('path/to.xsd')
    } 
    
    推荐文章