首页 > 解决方案 > 使用 jinja2 占位符动态更新 xml 文件,其值使用 python 存储在单独的 yaml 文件中

问题描述

可能对某人有益

用例:从存储在单独 yaml 文件中的变量动态更新 xml 配置文件

文件结构:我在一个目录(service/configs/template(s).xml)中有多个 xml 配置文件,每个文件都有多个 jinja2 占位符。1个文件例如:

<?xml version="1.0" encoding="UTF-8"?>
<GatewayConfiguration>
    <LogCategory>{{log_category}}</LogCategory>
</GatewayConfiguration>

变量位于单独的 yaml 文件 (service/variables/value_list.yml) - 1 个示例:

---
log_category: abc

问题陈述:在我的 AzDO 管道运行时,我需要使用 jinja2 替换使用合适的变量更新 xml 配置文件

解决方案:

import os
import yaml
from jinja2 import Template

with open(r'/service/variables/value.yaml') as file:
  value_list = yaml.load(file, Loader=yaml.FullLoader)

directory = os.listdir('/service/configs')
os.chdir('/service/configs')

for file in directory:
  with open(file, 'r+') as open_file:
    read_file = open_file.read()

    template = (read_file)
    j2_template = Template(template)
    print(j2_template.render(value_list))

标签: pythonxmljinja2

解决方案


推荐阅读