[英]Changing tag data in an XML file using windows batch file
我有一个包含多个标签的XML文件,我试图用批处理脚本更改其中一个标签的内容。
xml文件的一个示例是:
<ConfigurationData>
<ReportsFolder>\Reports</ReportsFolder>
<Helpfolder>\Help</HelpFolder>
<InstallationType>Terminal</InstallationType>
<LicenseFolder>..\License</LicenseFolder>
</ConfigurationData>
我正在尝试将<InstallationType>
和</InstallationType>
之间的数据更改为我选择的另一个变量。 我想我需要某种For循环来找到xml文件的那一部分,但是我对如何编辑那一部分感到很遗憾。
您真的应该使用专门设计用于操作XML的工具。
但是,在紧要关头,您可以使用任何可以执行正则表达式搜索和替换的工具来执行一个天真的解决方案,该解决方案可以在文件布局时使用该文件,但可能会因逻辑上等效的XML文件而失败布局重新排列。
我喜欢使用一个名为REPL.BAT的混合JScript /批处理实用程序来通过批处理脚本来处理文本文件。 该脚本将在XP之后的任何本机Windows计算机上运行,并且不需要安装任何第三方可执行文件。 单击链接以获取脚本代码和更全面的描述。
使用REPL.BAT,快速,高效但天真的解决方案就像:
setlocal enableDelayedExpansion
set "newValue=myNewValue"
type "fileName.xml"|repl "(<InstallationType>).*(</InstallationType>)" "$1!newValue!$2" >fileName.xml.new
move /y "fileName.xml.new" "fileName.xml"
@echo off
setlocal EnableDelayedExpansion
set anotherVariable=New value
(for /F "delims=" %%a in (theFile.xml) do (
set "line=%%a"
set "newLine=!line:InstallationType>=!"
if "!newLine!" neq "!line!" (
set "newLine=<InstallationType>%anotherVariable%</InstallationType>"
)
echo !newLine!
)) > newFile.xml
使用示例数据输出:
<ConfigurationData>
<ReportsFolder>\Reports</ReportsFolder>
<Helpfolder>\Help</HelpFolder>
<InstallationType>New value</InstallationType>
<LicenseFolder>..\License</LicenseFolder>
</ConfigurationData>
sed "/InstallationType/s/>[^<]*</>New Value</" file.xml
..output:
<ConfigurationData>
<ReportsFolder>\Reports</ReportsFolder>
<Helpfolder>\Help</HelpFolder>
<InstallationType>New Value</InstallationType>
<LicenseFolder>..\License</LicenseFolder>
</ConfigurationData>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.