C#环境下如何用Velocity语法实现Telosys目录文件遍历?
解决方案:借助
json-from-file.vm实现批量JSON转.entity文件 一、Telosys环境下的批量处理方案
Telosys的Velocity原生没有目录扫描函数,但可以通过外部脚本生成命令列表+模板参数化调用实现批量转换,步骤如下:
扩展你的
telosys-cmd.txt脚本
编写批处理/Shell脚本,遍历TelosysTools\templates\json-to-entity目录下的所有JSON文件,自动生成实体创建和模板调用命令。以Windows批处理为例:@echo off setlocal enabledelayedexpansion :: 定义JSON目录和目标模板路径 set JSON_DIR=TelosysTools\templates\json-to-entity set TEMPLATE=json-from-file.vm :: 遍历所有JSON文件,生成Telosys命令 for %%f in (%JSON_DIR%\*.json) do ( :: 提取文件名(不含后缀)作为实体名 set "ENTITY_NAME=%%~nf" :: 添加创建空实体的命令 echo ne !ENTITY_NAME! >> telosys-cmd.txt :: 添加调用模板处理JSON的命令(传递文件路径和实体名参数) echo apply !TEMPLATE! -p jsonPath="%%f" -p entityName="!ENTITY_NAME!" >> telosys-cmd.txt )执行这个批处理后,
telosys-cmd.txt会自动填充所有需要的命令。修改
json-from-file.vm模板
让模板接收传入的jsonPath和entityName参数,读取JSON内容并转换为.entity格式内容(以下是基础框架,可根据你的JSON结构调整转换逻辑)::: 读取JSON文件内容 #set($jsonContent = $fn.fileFromBundle($jsonPath)) :: 解析JSON(结合Telosys内置JSON工具) #set($entityData = $fn.jsonParse($jsonContent)) :: 构建.entity文件内容 #set($entityContent = "entity $entityName {") #foreach($field in $entityData.fields) #set($entityContent = $entityContent + "\n $field.type $field.name;") #end #set($entityContent = $entityContent + "\n}") :: 写入目标.entity文件 $fn.writeFile($entityName + ".entity", $entityContent)执行Telosys命令脚本
在Telosys工具中加载并执行telosys-cmd.txt,即可批量完成实体创建和JSON转换。
二、C#环境下Velocity目录遍历的扩展方案
如果后续需要在纯C#环境中用Velocity实现目录遍历,可以自定义Velocity工具类补充功能:
编写C#工具类
using System.IO; using System.Collections.Generic; public class VelocityFileSystemHelper { public IEnumerable<string> GetFiles(string directoryPath, string searchPattern = "*.json") { return Directory.EnumerateFiles(directoryPath, searchPattern); } }将工具类注入Velocity上下文
using Apache.Velocity; using Apache.Velocity.App; var velocityEngine = new VelocityEngine(); velocityEngine.Init(); var context = new VelocityContext(); context.Put("fileHelper", new VelocityFileSystemHelper()); // 加载模板并执行渲染 var template = velocityEngine.GetTemplate("your-template.vm"); // 后续渲染逻辑...在Velocity模板中调用
#foreach($filePath in $fileHelper.GetFiles("TelosysTools/templates/json-to-entity")) #处理单个JSON文件,例如读取内容、转换格式 #set($jsonContent = $fn.readFile($filePath)) #... #end
内容的提问来源于stack exchange,提问作者saibin
相关产品推荐
相关产品推荐

