java根据xml模板生成对应的xml

简介

根据xml模板动态填充xml;在网上找了很多跟我需要的都不一样,自己在这写一下,源码地址拿来改一下模板就可以直接使用

代码

核心依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

xml模板

<?xml version="1.0" encoding="utf-8"?>
<INFO>这就是一个简单的模板</INFO>
<Profile>
<ID>${id!''}</ID>
<Name>${name!''}</Name>

<#list demoList as list>
<Demo>
    <Subject>${list.subject}</Subject>
    <Score>${list.score}</Score>
</Demo>
</#list>

</Profile>

代码

package com.fanqiechaodan.generator.controller;

import com.fanqiechaodan.generator.model.Demo;
import com.fanqiechaodan.generator.model.XMLModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Classname XMLController
 * @Description
 * @Date 2022/6/19 19:10
 * @Author: fanqiechaodan
 */
@RestController
@RequestMapping(value = "/xml")
@Slf4j
public class XMLController {

    @GetMapping(value = "/generator")
    public void generator() {
        List<Demo> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Demo demo = new Demo();
            demo.setScore(60 + i);
            demo.setSubject("subject" + i);
            list.add(demo);
        }
        XMLModel xmlModel = new XMLModel();
        xmlModel.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        xmlModel.setName("张三");
        xmlModel.setDemoList(list);
        xml2XmlDoc(xmlModel, "src\\main\\resources\\template\\template.xml", "src\\main\\resources\\template\\newTemplate.xml");
    }

    /**
     * 将xml模板转换为newxml
     *
     * @param model           需要填充到模板的数据
     * @param templetFilePath 模板文件路径
     * @param targetFilePath  目标文件保存路径
     */
    public static void xml2XmlDoc(XMLModel model, String templetFilePath, String targetFilePath) {
        Writer out = null;
        try {
            // 将模板文件路径拆分为文件夹路径和文件名称
            String tempLetDir = templetFilePath.substring(0, templetFilePath.lastIndexOf("\\"));
            // 注意:templetFilePath.lastIndexOf("/")中,有的文件分隔符为:\ 要注意文件路径的分隔符
            String templetName = templetFilePath.substring(templetFilePath.lastIndexOf("\\") + 1);
            // 将目标文件保存路径拆分为文件夹路径和文件名称
            String targetDir = targetFilePath.substring(0, targetFilePath.lastIndexOf("\\"));
            String targetName = targetFilePath.substring(targetFilePath.lastIndexOf("\\") + 1);
            Configuration configuration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
            configuration.setDefaultEncoding(String.valueOf(StandardCharsets.UTF_8));
            // 如果目标文件目录不存在创建
            File file = new File(targetDir);
            if (!file.exists()) {
                file.mkdirs();
            }
            //加载模板数据(从文件路径中获取文件)
            configuration.setDirectoryForTemplateLoading(new File(tempLetDir));
            //获取模板实例
            Template template = configuration.getTemplate(templetName);
            File outFile = new File(targetDir + File.separator + targetName);
            //模板和数据模型合并生成文件
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), StandardCharsets.UTF_8));
            //生成文件
            template.process(model, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("write xml failed:", e);
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("close out failed:", e);
                }
            }
        }
    }
}

测试

在这里插入图片描述
在这里插入图片描述

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,使用Java实现自动生成行为树xml文件的过程可以分为以下几个步骤: 1. 定义行为树的节点类型和基本结构。可以使用枚举类型来定义节点类型,使用类来定义节点信息,包括节点名称、节点类型、节点参数等。 ```java public enum NodeType { Selector, Sequence, Condition, Action } public class Node { private String name; private NodeType type; private Map<String, Object> params; private List<Node> children; // getters and setters } ``` 2. 编写行为树的生成器。可以使用递归的方式,遍历所有节点并根据节点类型生成对应xml元素。 ```java public class BehaviorTreeGenerator { public static Element generate(Node node) { Element element; switch (node.getType()) { case Selector: element = new Element("Selector"); break; case Sequence: element = new Element("Sequence"); break; case Condition: element = new Element("Condition"); break; case Action: element = new Element("Action"); break; default: throw new RuntimeException("Invalid node type: " + node.getType()); } element.setAttribute("name", node.getName()); // add parameters for (Map.Entry<String, Object> entry : node.getParams().entrySet()) { element.setAttribute(entry.getKey(), entry.getValue().toString()); } // add children for (Node child : node.getChildren()) { element.addContent(generate(child)); } return element; } } ``` 3. 使用生成器来生成xml文件。可以使用JDOM库来创建xml文件和元素,并将生成的节点树添加到xml文件中。 ```java public class Main { public static void main(String[] args) { Node root = new Node("root", NodeType.Selector); Node condition = new Node("condition", NodeType.Condition); condition.getParams().put("param1", "value1"); Node action = new Node("action", NodeType.Action); action.getParams().put("param2", "value2"); root.getChildren().add(condition); root.getChildren().add(action); Element rootElement = new Element("BehaviorTree"); rootElement.addContent(BehaviorTreeGenerator.generate(root)); Document doc = new Document(rootElement); XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); try { outputter.output(doc, new FileOutputStream("behavior_tree.xml")); } catch (IOException e) { e.printStackTrace(); } } } ``` 这样就可以根据模板自动生成行为树xml文件了。需要注意的是,生成器的实现和xml文件的格式可以根据具体需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

.番茄炒蛋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值