使用bat操作替换XML文件的字符串

发布时间 2023-04-18 15:41:41作者: log9527
使用bat脚本,替换xml的字符串,并且生成一个新文件
@echo off
setlocal enabledelayedexpansion

set old_str=123
set new_str=456
set input_file=123.xml
set output_file=456.xml

set "file_content="

for /f "delims=" %%a in (%input_file%) do (
    set "line=%%a"
    set "line=!line:%old_str%=%new_str%!"
    set "file_content=!file_content!!line!"
)

echo !file_content!>%output_file%

如果提示“系统找不到文件 123.xml”,修改为

set input_file=%~dp0\123.xml

或者在前面添加

rem 进入当前路径
cd /d %~dp0

注意:

1. bat脚本文本格式改成ASCII,不然中文乱码

2. xml文件格式需要utf-8,并且xml的文件头也必须是utf-8

<?xml version="1.0" encoding="utf-8"?>

如果希望生成的xml文件格式被认为utf-16,可以在前面的字符串替换增加

set "line=!line:utf-8=utf-16!"