Windows 10

Batch File To Read XML File

In this tutorial, you’ll learn how to read values from an XML file using a batch script and the command-line utility XML.EXE (part of XMLStarlet). Since native batch scripting has limited support for XML parsing, we’ll use XMLStar to extract data using XPath.
 

📂 Sample XML File:

Save the following content as file.xml:

<?xml version="1.0" encoding="utf-8"?>
<person>
    <name>
        Alex
    </name>
    <age>
        20
    </age>
    <address>
        Boston
    </address>
</person>

 
 

⚙️ Prerequisite: Download XML.EXE

To process XML files in a batch script, download XMLStar from:
🔗 http://xmlstar.sourceforge.net/download.php
Make sure XML.EXE is accessible via the system PATH or located in the same directory as your batch file.
 

💡 Batch File to Read XML Element

This batch script extracts the <name> tag value from file.xml:

@echo off
for /f %%i in ('XML.EXE sel -t -v "//name" file.xml') do set var=%%i
echo Name is %var%

🖨️ Output:

Name is Alex

 

📝 Explanation

XML.EXE sel -t -v "//name" file.xml ➤ Uses XPath to select the content of the <name> element.

for /f %%i in (...) do set var=%%i ➤ Captures the output of the XML query and assigns it to a variable.

echo Name is %var% ➤ Displays the extracted XML data.
 

✅ Use Cases
  • Automate configuration reading
  • Extract data from structured logs
  • Integrate batch scripts with XML-based systems

 

📌 Summary

While Windows batch scripts don’t natively support XML parsing, tools like XMLStar make it possible to extract values easily using XPath. It’s a lightweight and efficient solution for script-based automation involving XML files.
 

Leave a Reply

Your email address will not be published. Required fields are marked *