Bulk Replace
Web and code

How to Find and Replace Values in Many XML and JSON Files Safely

Change a value, attribute or key across many XML and JSON files without breaking them. Patterns that respect quotes and escaping, and how to validate.

Updated 5 minute read The Bulk Replace team

To find and replace a value in multiple XML or JSON files safely, match the value together with its context, such as the attribute name or key, rather than the value on its own. For example, find version="1\.2" instead of 1.2, or (?<="timeout"\s*:\s*)30\b instead of 30. Make sure any new text is escaped the way the format requires (&amp; in XML, \" and \\ in JSON), keep each file's encoding, and then parse every changed file to prove it is still valid. A text replace is fast and keeps the formatting and comments exactly as they were, which a load-and-save script often does not.

Below are patterns for the common jobs, the escaping rules for both formats, and a PowerShell snippet that validates a whole folder in seconds.

Why context matters

XML and JSON files are full of short values that repeat: version numbers, true and false, small integers, IDs. Replacing 1.2 everywhere will change a dependency version, a schema version and a coordinate in the same file. Anchoring the match to its key or attribute is the single biggest safety step.

GoalToo broadBetter
Bump one attribute1.2version="1\.2" → version="1.3"
Change a JSON setting30(?<="timeout"\s*:\s*)30\b → 60
Rename an elementitem<(/?)item\b → <$1entry
Rename a JSON keyuserName"userName"(?=\s*:) → "username"
Flip a booleanfalse("debug"\s*:\s*)true\b → $1false

The \s* around the colon in the JSON patterns allows for both "timeout":30 and "timeout" : 30, so differently formatted files all match. The \b after the number stops 30 matching the start of 300. The lookahead (?=\s*:) in the key rename means "only where this string is a key", so a value that happens to be the text userName is not touched.

One attribute on one element

If the same attribute name appears on several elements, add the element to the pattern. To change the version only on <dependency> elements:

  • Find: (?<=<dependency\b[^>]*\bversion=")1\.2(?=")
  • Replace: 1.3

The lookbehind checks that the value sits inside a <dependency tag after version=", and [^>]* lets other attributes come first, but stops at the end of the tag. Variable-length lookbehind like this works in .NET (PowerShell) and JavaScript (VS Code). In Notepad++, which does not allow it, capture the start instead: find (<dependency\b[^>]*\bversion=")1\.2" and replace with ${1}1.3". The braces matter there, because $11 could be read as group 11. The backreference syntax guide covers this trap.

This works when each tag is on one line or when attributes are written in a consistent order. XML allows attributes in any order and tags that span lines; if your files are that varied, check the match count against the number of elements you expect.

Escaping rules for new values

A replacement can be perfectly placed and still break a file if the new text contains characters the format reserves.

CharacterIn XML text and attributesIn a JSON string
&&amp;As is
<&lt;As is
>&gt; (recommended)As is
"&quot; inside a double-quoted attribute\"
'&apos; inside a single-quoted attributeAs is
\As is\\
Line breakAs is in text\n

The most common breakage is a company name with an ampersand going into XML, or a Windows path going into JSON with single backslashes. C:\Temp in JSON must be written C:\\Temp; a single \T is an invalid escape and the file will not parse. Moving paths around is covered in updating file paths in multiple files.

Encoding and the XML declaration

An XML file often starts with a declaration such as <?xml version="1.0" encoding="utf-8"?>. The bytes in the file must match what that line says. If a tool reads a UTF-8 file and writes it back as ANSI, any accented characters become invalid and the parser will reject the file. JSON should be UTF-8, and some parsers reject a byte order mark at the start. Use a tool that keeps each file's encoding, or set the encoding explicitly when you write. See UTF-8 vs ANSI vs UTF-16 for how to tell them apart.

Validate every changed file

After the replace, parse each file. In PowerShell, from the top folder:

foreach ($f in Get-ChildItem -Recurse -File -Filter *.json) { try { Get-Content $f.FullName -Raw | ConvertFrom-Json -ErrorAction Stop | Out-Null } catch { "Invalid JSON: $($f.FullName)" } }

foreach ($f in Get-ChildItem -Recurse -File -Filter *.xml) { try { [xml](Get-Content $f.FullName -Raw) | Out-Null } catch { "Invalid XML: $($f.FullName)" } }

Each command prints only the files that fail to parse. No output means every file is well formed. Two notes: Windows PowerShell 5.1's ConvertFrom-Json rejects comments and trailing commas, which some config files allow, so a file listed there may still be fine for its own program. And these checks confirm the file is well formed, not that the values are right for your application, so run the program afterwards too.

Text replace vs load-and-save scripts

You could load each file with a parser, change the value and save it. That guarantees valid output, but it has costs:

  • Formatting and indentation are often rewritten.
  • Comments in XML may be preserved, but JSON parsers drop them.
  • Attribute order, quote style and number formats can change, which makes the diff huge.

A targeted text replace changes only the matched characters, so the diff shows exactly what you meant to change. Combined with a validation pass, it is usually the better choice for bulk edits to files that people read and review.

Doing it across a folder

Bulk Replace runs regex rules like the ones above across every .xml, .json, .config or .csproj file in a folder tree, with a before/after diff that shows each changed value in context. It detects and preserves each file's encoding, which protects the XML declaration and avoids adding a byte order mark to JSON. Bulk Replace backs up every run, so if a validation check turns up a broken file, one click restores the originals while you fix the pattern.

Checklist

  1. Back up or commit.
  2. Match the key, attribute or element along with the value.
  3. Escape new text for the format.
  4. Preview and check the match count.
  5. Replace, then parse every changed file.
  6. Run the program that reads the files.

Frequently asked questions

How do I change one attribute value in many XML files?

Match the attribute name together with its value, such as version="1\.2", rather than the value alone, so other attributes with the same value are not touched.

What characters need escaping in XML and JSON?

In XML text, & must be written as &amp; and < as &lt;. In JSON strings, double quotes and backslashes must be escaped with a backslash.

How do I check the files are still valid?

In PowerShell, Get-Content file.json -Raw | ConvertFrom-Json and [xml](Get-Content file.xml -Raw) both fail with an error on an invalid file.

Get three guides like this every month, plus software update notices.Subscribe →