python - 使用 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))
解决方案
推荐阅读
- go - 递归扩展包含指针的结构定义
- google-cloud-platform - BigQuery API CopyJobConfiguration 添加源和目标 project_id
- list - 在图形的cpp实现中,节点应该存储在模板向量还是列表中?
- android - 默认启动器已设置,但不适用于其他用户
- c# - C# 空 WebClient 下载字符串
- nativescript - Nativescript 图像区域协调点击事件,如 HTML Image Map
- php - 如何使用 USB 令牌使用 PHP 和 chrome 令牌签名扩展在 pdf 中应用数字签名?
- javascript - Calling Javascript function from external file when loading html page
- c# - 使用 datatable() 计算 C# 表单文本框字符串
- csv - PySpark:如何用逗号指定列作为十进制