问题
I have the following "file.xml":
<root>
<cities>
<cityName>paris</cityName>
<cityName>london</cityName>
<cityName>...</cityName>
...
</cities>
<countries>
<countryName>india</countryName>
<countryName>japon</countryName>
<countryName>...</countryName>
...
</countries>
<continents>
<continentName type="geo">asia</continentName>
<continentName type="geo">america</continentName>
<continentName type"geo">...</continentName>
...
</continents>
</root>
I would like to get with a batch file all the content of a specified tag and also all the specified tag's attributes(key and value) and write in a file. For example, I specify "continentName" in my batch file, so I would have a "file.txt" with :
type geo asia
type geo america
type geo ...
This is what I have for the moment (I only get tags content, not attributes) :
@echo off
setlocal enabledelayedexpansion enableextensions
set tag=continentName
set f_xml=file.xml
set tag2=/%tag%
for /f "tokens=2-4delims=<>" %%a in (%f_xml%) do (
IF "%%a"=="%tag%" IF "%%c"=="%tag2%" ECHO(%%b>>file.txt
)
回答1:
@ECHO OFF
setlocal enabledelayedexpansion enableextensions
set tag=continentName
set f_xml=q23655846.txt
set tag2=/%tag%
for /f "tokens=2-4delims=<>" %%a in (%f_xml%) do (
IF "%%a"=="%tag%" IF "%%c"=="%tag2%" ECHO(%%b
)
GOTO :eof
This should get your output. I used a file named q23655846.txt
containing your data for my testing.
回答2:
EDIT: Solution changed as reply to new specifications
I changed the original Batch program to fulfill the new request:
@echo off
set tag=continentName
set f_xml=file.xml
(for /F "tokens=3,4 delims=<=>" %%a in ('findstr "\</%tag%\>" %f_xml%') do echo %%~a %%b) > file.txt
This program works only with the .xml file as shown above (I mean, at the moment I wrote this solution) and with this requested output:
geo asia
geo america
geo ...
If the file is changed (like inserting more attributes, or placing none attribute, or splitting the continentName tag in several lines, etc), or the output is changed, previous solution will not work.
来源:https://stackoverflow.com/questions/23655846/get-content-of-xml-tags-with-batch-file-updatedgetting-also-tags-attributes