Skip to main content

How to Read a Specific Value from an XML File in Batch Script

Extensible Markup Language (XML) relies on strict opening and closing tags to define data hierarchies. When writing automation scripts that rely on configuration files (like web.config or MSBuild .csproj files), extracting a specific setting, like a database connection string or a version number, is a common necessity.

Because pure Batch lacks native XML parsing tools, attempting to extract values using FINDSTR is extremely unreliable (it breaks if the XML spans multiple lines or changes formatting). In this guide, we will demonstrate how to read a specific XML value robustly using a PowerShell bridge.

Setup: A Sample XML File (config.xml)

Create a test file named config.xml with the following nested structure:

<?xml version="1.0" encoding="utf-8"?>
<Configuration>
<Environment>Production</Environment>
<Database>
<Server>db-prod-01.local</Server>
<Port>1433</Port>
<Timeout>30</Timeout>
</Database>
</Configuration>

Method 1: The PowerShell Bridge (Industry Standard)

PowerShell has a built-in [xml] type accelerator that converts raw text into a navigable object hierarchy. By wrapping this in a FOR /F loop, your Batch script can query exact XML nodes safely.

tip

Always pass -NoProfile when calling PowerShell from Batch. This prevents user-specific PowerShell profile scripts from loading, which improves startup time and prevents unexpected output from contaminating your captured values.

Implementation Script

@echo off
setlocal

set "xmlFile=config.xml"

:: Verify the file exists
if not exist "%xmlFile%" (
echo [ERROR] The file %xmlFile% was not found.
pause
exit /b 1
)

echo Extracting database settings...

:: 1. Read the file into an [xml] object.
:: 2. Navigate exactly to the node: Configuration -> Database -> Server
:: 3. The loop captures the output string into the variable %%A
for /f "delims=" %%A in ('powershell -NoProfile -Command "[xml]$doc = Get-Content -Path '%xmlFile%'; $doc.Configuration.Database.Server"') do set "dbServer=%%A"

for /f "delims=" %%A in ('powershell -NoProfile -Command "[xml]$doc = Get-Content -Path '%xmlFile%'; $doc.Configuration.Database.Port"') do set "dbPort=%%A"

:: Verify the extraction succeeded
if not defined dbServer (
echo [ERROR] Failed to extract database settings from %xmlFile%.
pause
exit /b 1
)

echo.
echo ==========================================
echo DATABASE SERVER: %dbServer%
echo DATABASE PORT: %dbPort%
echo ==========================================
pause

Method 2: Extracting XML Attributes

Sometimes the value you need isn't the text between the tags, but an attribute inside the tag itself. Create a test file named appInfo.xml:

<?xml version="1.0" encoding="utf-8"?>
<Application Version="2.4.1" Status="Active" />

PowerShell treats XML attributes exactly like child nodes.

@echo off
setlocal

set "xmlFile=appInfo.xml"

:: Verify the file exists
if not exist "%xmlFile%" (
echo [ERROR] The file %xmlFile% was not found.
pause
exit /b 1
)

:: Navigating directly to the 'Version' attribute
for /f "delims=" %%A in ('powershell -NoProfile -Command "[xml]$doc = Get-Content -Path '%xmlFile%'; $doc.Application.Version"') do set "appVersion=%%A"

echo Found Application Version: %appVersion%
pause

Why Read XML Values in Batch?

  1. Deployment Scripts: Reading a .csproj or pom.xml file to automatically assign the current compiled <Version> number to your output deployment .zip archive.
  2. IIS Automation: Querying the applicationHost.config XML file to retrieve the exact <physicalPath> of a website before triggering a backup routine.
  3. Third-Party Tool Interfaces: Reading the <ExitCode> tag from an XML report generated by an antivirus scanner or a unit testing framework natively within your control flow.

Important Considerations

  • Namespaces: If your XML file contains namespaces (e.g., <ns:Configuration xmlns:ns="http...">), the simple dot-notation in PowerShell will fail. You must use Select-Xml with XPath queries, which dramatically complicates the syntax.

  • Case Sensitivity: XML tags are strictly case-sensitive. $doc.Configuration works, but $doc.configuration will return null and fail if the source tag is capitalized.

  • Invalid XML: If someone manually edited config.xml and forgot to close a tag (e.g., <Port>1433), the PowerShell [xml] cast will throw a fatal parsing error, preventing your script from extracting incorrect or partial data.

Conclusion

Querying specific values from XML files elevates Batch scripts from blind sequential executors into context-aware automation tools. By actively side-stepping the fragility of text-based FINDSTR matching and relying on PowerShell's robust [xml] object serialization, you can comfortably retrieve exact settings hidden deep within complex hierarchical configurations.