How to replace the values/text in XML file using PowerShell

Abstract: Replace values in XML files using PowerShell while preserving special characters and preventing encoding errors.

Created: 2026-10-16 by
Use PowerShell to load your XML file into an object model, traverse the nodes using XPath or direct property access, modify the .Value or .InnerText properties, and then save the document back to disk. This approach ensures that special characters like backslashes, colons, semicolons, single quotes, and double quotes are handled correctly by the underlying .NET XML parser, preventing malformed output or encoding errors during the replacement process.

Loading the XML Document

The first step in any XML manipulation task is loading the file content into a structured object. In PowerShell, you can use the [xml] type accelerator to cast a string containing XML content into an System.Xml.XmlDocument object. This allows you to interact with the data as if it were a native PowerShell object rather than a raw text string. To begin, read the file content and assign it to the variable. You should specify the encoding explicitly if you know it, though [xml] defaults to UTF-8 in most modern contexts. If the file contains special characters, ensure they are properly escaped in the source file before loading.
$xmlPath = "C:\Data\config.xml"
$xmlContent = Get-Content -Path $xmlPath -Raw
[xml]$xmlDoc = $xmlContent
By using the -Raw parameter, you read the entire file as a single string, which is necessary for the [xml] conversion. Once loaded, you can inspect the structure of the XML object in the console to understand its hierarchy. This method is robust because it validates the XML structure immediately; if the file is malformed, PowerShell will throw an error at this stage, saving you from processing corrupted data. For more complex scenarios involving large files, consider checking related guides on handling file paths and special characters, such as our article on File path in XML: Understanding how to handle special characters, which details best practices for ensuring path integrity within XML attributes.

Identifying Nodes to Replace

Before replacing values, you must identify exactly which nodes need modification. XML documents are hierarchical trees composed of elements, attributes, and text nodes. PowerShell provides several ways to locate these nodes, primarily through XPath queries or by navigating the object properties directly. If you know the specific tag name, you can use the SelectNodes method with an XPath expression. This is ideal when you need to replace multiple instances of a value across different parts of the document. For example, to find all elements named setting, you would use:
$nodes = $xmlDoc.SelectNodes("//setting")
Alternatively, if the structure is fixed and shallow, you can navigate directly using dot notation. For instance, if your XML has a root element configuration with a child database, you might access it via $xmlDoc.configuration.database. Direct navigation is faster for simple scripts but less flexible for dynamic structures. Always verify the node count before proceeding to ensure you are targeting the correct data.

Performing the Replacement

Once you have selected the target nodes, you can update their content. The key distinction is between modifying the InnerText (or Value) for text content and modifying attribute properties for metadata. When updating text, simply assign the new string to the InnerText property.
foreach ($node in $nodes) {
    $node.InnerText = "New Value Here"
}
This operation updates the object in memory. It does not write to the file yet. If your replacement string contains special characters such as double quotes (") or ampersands (&), the System.Xml.XmlDocument class handles the escaping automatically when you later serialize the document. This prevents common issues where manual string replacement results in invalid XML syntax. However, be cautious with single quotes and backslashes; while they do not break XML validity, they may affect how the data is interpreted by downstream applications. For cases where you need to preserve formatting or handle complex transformations, refer to resources on exporting data formats, such as Exporting same format to CSV, to understand broader data transformation principles that apply to XML as well.

Saving the Modified XML

After making changes, you must persist them to disk. Use the Save method on the XmlDocument object, passing the original file path or a new destination. This method writes the current state of the object tree back to an XML file, applying proper indentation and encoding headers.
$xmlDoc.Save($xmlPath)
It is good practice to create a backup of the original file before overwriting it. You can achieve this by copying the file to a timestamped location or using a temporary variable to hold the original content. Additionally, always validate the saved file after writing, especially if the replacement involved complex logic or special characters, to ensure no corruption occurred during the serialization process.

Frequently Asked Questions

How do I handle special characters like ampersands in my replacement text?

Do not manually escape special characters like & or < before assigning them to InnerText. The System.Xml.XmlDocument class automatically escapes these characters when you call the Save method. Manually escaping them can lead to double-encoding issues, resulting in visible escape codes in your final file.

Can I replace XML attributes instead of element text?

Yes, you can modify attributes by accessing them as properties of the node object. For example, if you have a node with an attribute named id, you can change it using $node.id = "newValue". This updates the attribute value in the object model just like changing text content.

What happens if the XPath query returns no nodes?

If the query returns no nodes, the collection will be empty, and your loop will not execute. This is a safe behavior, but you should check the count of returned nodes before proceeding if you expect specific data to exist. Failing to find nodes usually indicates an incorrect XPath expression or a mismatched namespace.

Is there a performance difference between SelectNodes and direct property access?

Direct property access is generally faster for small, known structures because it avoids the overhead of parsing an XPath string. However, SelectNodes is more powerful for finding nodes across deep or irregular hierarchies. For most configuration file replacements, either method performs instantly.

How do I preserve the XML declaration when saving?

The Save method preserves the XML declaration (e.g., <?xml version="1.0"?>) if it was present in the original loaded document. If you created the document from scratch, you may need to set the XmlDeclaration property manually before saving to ensure the header is included.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More