Jawwalcom
Jawwalcom

Reputation: 183

A batch file to extract the value of a specific XML tag

**I need a batch file that retrieves the Data tag value only (without the tag name) and writes it down into a .txt file. This file might have more XML tags than those listed.

So the output should be:

Capital gains are the key ingredient of income disparity in the US-- and the force behind the winner takes all mantra of our economic system. If you want even out earning power in the U.S, you have to raise the 15% capital gains tax.**

My file looks like this :**

<TABLE>
Table 30
<ROW>
Multiple Rows
<DATA>
Capital gains are the key ingredient of income disparity in the US-- and the force  
behind the winner takes all mantra of our economic system. If you want  even out 
earning power in the U.S, you have to raise the 15% capital gains tax.
</DATA>
</ROW>
</TABLE>

Upvotes: 2

Views: 8978

Answers (1)

kikuchiyo
kikuchiyo

Reputation: 3421

I don't have a windows machine, so forgive if the syntax is a little off, but something like this may help, if the data is as you listed in your example, though you may want to consider using Powershell, as it has excellent tools for dealing with XML:

setlocal enabledelayedexpansion
set start_reading="0"
set stop_reading="0"
set your_file_name=%~1

if EXIST "%your_file_name%.txt" del "%your_file_name%.txt"

for /f "eol=; tokens=1 delims=" %%c in ('type "%your_file_name_here%.xml"') do (
  set line=%%c

  @REM Determine if at start of Data Tag
  for /f "eol=; tokens=1 delims=" %%d in ('echo !line! ^| findstr /i /c:"<DATA>"') do (
    set start_reading="1"
  )

  @REM Determine if at end of Data Tag
  for /f "eol=; tokens=1 delims=" %%d in ('echo !line! ^| findstr /i /c:"</DATA>"') do (
    set stop_reading="1"
  )

  @REM stop reading DATA tag input
  if "!stop_reading!"=="1" (
    set start_reading="0"
  )

  @REM skips first line assumed to be <DATA>
  if "!start_reading!"=="2" (
    echo !line! >> "%your_file_name_here%.txt"
  )

  @REM Ready to start reading post <DATA> line
  if "!start_reading!"=="1" (
    set stop_reading="0"
    set start_reading="2"
  )

)

@REM Check results
type "%your_file_name_here%.txt"

Let me know if you need help. I have had to work in environments, where DOS was all they would let us use, so I feel your pain. Good luck! :)

Upvotes: 1

Related Questions