简体   繁体   中英

Changing tag data in an XML file using windows batch file

I have an XML file with several tags in it, and I am trying to change the contents of one of these tags with a batch script.

An example of the xml file is:

<ConfigurationData>
<ReportsFolder>\Reports</ReportsFolder>
<Helpfolder>\Help</HelpFolder>
<InstallationType>Terminal</InstallationType>
<LicenseFolder>..\License</LicenseFolder>
</ConfigurationData>

I am trying to change the data between <InstallationType> and </InstallationType> to another variable of my choosing. I'm thinking I would need some sort of For loop to find that part of the xml file, but I'm lost as to how I would edit just that one section.

You really should use a tool that is designed specifically to manipulate XML.

But in a pinch, you could use any tool that can do a regex search and replace to do a naive solution that would work with the file as you have it laid out, but might fail with a logically equivalent XML file that has had the physical layout rearranged.

I like to use a hybrid JScript/batch utility I wrote called REPL.BAT to manipulate text files via batch scripts. The script will run on any native Windows machine from XP onward, and it does not require installation of any 3rd party executables. Click the link to get the script code and a more thorough description.

Using REPL.BAT, a fast and efficient but naive solution is as simple as:

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

Output with your example data:

<ConfigurationData>
<ReportsFolder>\Reports</ReportsFolder>
<Helpfolder>\Help</HelpFolder>
<InstallationType>New value</InstallationType>
<LicenseFolder>..\License</LicenseFolder>
</ConfigurationData>

GNU sed

sed "/InstallationType/s/>[^<]*</>New Value</" file.xml

..output:

<ConfigurationData>
<ReportsFolder>\Reports</ReportsFolder>
<Helpfolder>\Help</HelpFolder>
<InstallationType>New Value</InstallationType>
<LicenseFolder>..\License</LicenseFolder>
</ConfigurationData>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM