加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

生成和解析xml的利器

发布时间:2020-12-15 23:23:53 所属栏目:百科 来源:网络整理
导读:import groovy.xml.MarkupBuilder //该文件用于生成本地xml配置文件 def toDimens(String filePath,String targetPath) { def file = new File(targetPath) if (file.exists()) file.delete() def writer = file.newPrintWriter() def xml = new MarkupBuild

import groovy.xml.MarkupBuilder
//该文件用于生成本地xml配置文件
def toDimens(String filePath,String targetPath) {
def file = new File(targetPath)
if (file.exists())
file.delete()
def writer = file.newPrintWriter()
def xml = new MarkupBuilder(writer)
//生成xml文件
writer.append('<?xml version="1.0" encoding="utf-8"?> n')
xml.resources {
new File(filePath).eachLine{line->
bits = line.tokenize("=")
try {
dimen(name:bits[0].trim(),bits[1].trim())


} catch (Exception e) {
//exceptions pah!
}
}
}
writer.flush()
//控制台输出文件信息
println writer.toString()
writer.close()
}



java调用groovy:

/**

* 生成xml文件 * * @param filePath * 源文件 * @param targetPath * 生成文件路径 * @param type * 生成配置文件的类型 */ public static void pro2xml(String filePath,String targetPath,int type) { // System.out.println("============生成xml文件==========="); ClassLoader parent = Utils.class.getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); try { GroovyObject groovyObject = null; File tempFile = new File(Constants.GROOVY_PATH); // 加载类S Class<?> groovyClass = loader.parseClass(tempFile); groovyObject = (GroovyObject) groovyClass.newInstance(); System.out.println("-> " + groovyObject.getClass()); if (type == Constants.METHOD_TODIMENS) { groovyObject.invokeMethod("toDimens",new Object[] { filePath,targetPath }); } else if (type == Constants.METHOD_TOARRAY) { groovyObject.invokeMethod("toArray",targetPath }); } else { groovyObject.invokeMethod("toString",targetPath }); } // 执行 groovy方法,生成xml配置文件 GroovyShell gShell = new GroovyShell(parent); gShell.setVariable("filePath",filePath); gShell.setVariable("targetPath",targetPath); gShell.evaluate(tempFile); } catch (Exception e) { e.printStackTrace(); } finally { // 删除properties文件 // File file = new File(filePath); // if (file.exists()) { // file.delete(); // } } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读