您的位置:首页 > 其它

生成和解析xml的利器

2013-09-28 09:17 85 查看
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", new Object[] { filePath, targetPath });

} else {

groovyObject.invokeMethod("toString", new Object[] { filePath, 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();

// }

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: