Sub topic 5
Keeping the XML valid while you edit
This chapter assumes you can read Git conflict markers (previous chapter), know the layout of a Salesforce DX project, and can run sf commands against a sandbox or scratch org. It covers what can go wrong in the XML while you resolve a conflict, and how to catch each problem before it reaches the org.
Well-formed is not the same as valid
Two separate checks apply to a metadata file.
- Well-formed means the file obeys XML syntax. Every tag closes, tags nest correctly, special characters are escaped, and there is one root element. Any XML parser can check this.
- Valid for Salesforce means the content makes sense to the Metadata API. Element names must exist for that metadata type, values must be allowed, and the same item must not appear twice. Only a deployment, or a script that knows the type, can check this.
A file can pass the first check and fail the second. Git knows about neither. It merges text lines, so it can produce a clean merge with no conflict markers that still contains broken XML or duplicate entries.
The usual ways a resolution breaks
Leftover marker lines
The three marker lines are plain text. If you keep both sides and forget to delete =======, the file is no longer XML. The parser reports an error at the first marker, and the error often points at a line that looks harmless.
Half-resolved blocks
Metadata blocks such as <fieldPermissions> span several lines. Git conflicts do not always split on block boundaries. When two edits touch neighbouring lines, a conflict region can start or end in the middle of a block. If you delete one side by line count, you can leave an orphaned closing tag:
<fieldPermissions>
<editable>true</editable>
<field>Account.Region__c</field>
<readable>true</readable>
</fieldPermissions>
<readable>true</readable>
</fieldPermissions>The second </fieldPermissions> has no matching opening tag. Parsers report this as a mismatched or unexpected tag. The fix is to resolve whole elements. Start and end your edit at element boundaries, and count the opening and closing tags in the region you kept.
Duplicate entries
This is the most common error after a "keep both sides" resolution. Suppose both branches grant access to Account.Tier__c, with slightly different settings. Git sees two different additions and keeps both. The file is well-formed, but it now holds two fieldPermissions entries for the same field. A deployment rejects it or applies only one of them, depending on the type.
Duplicates also appear in custom labels (two <labels> blocks with the same <fullName>), in permission sets (the same <apexClass> or <object> twice), and in profiles. When you keep both sides, always check that the identifying element (field, fullName, apexClass, name) is unique.
Unescaped characters
Inside text content, & and < must be written as & and <. This matters most in custom labels, flow formulas, and validation rules, where values contain operators. If you retype or paste a value during resolution, keep the escaped form.
<labels>
<fullName>Terms_Notice</fullName>
<language>en_US</language>
<protected>false</protected>
<shortDescription>Terms notice</shortDescription>
<value>Terms & Conditions apply when Amount < 1000</value>
</labels>A literal & in that value would make the whole file fail to parse.
Encoding, line endings and indentation
Salesforce source files are UTF-8 with LF line endings and four-space indentation. Some editors add a byte order mark, convert line endings, or turn indentation into tabs when you save. A BOM can break strict parsers. The other two make every line look changed in the next diff, which causes more conflicts later. Check your editor settings before you edit these files by hand.
Keep the structure when you edit by hand
- Edit whole elements. Never leave a block half open.
- Keep the XML declaration (
<?xml version="1.0" encoding="UTF-8"?>) as the first line, and keep the root element with itsxmlnsattribute. - Keep sibling elements in the order the CLI writes them. The retrieve command sorts them alphabetically in most types. If you append a block at the end instead, the next retrieve moves it, and the move shows up as a change.
- Do not reformat the file. Resolve the conflict and leave every other line as it was.
- Leave a newline at the end of the file.
Check the result in three steps
Run the cheap checks first. They take seconds, while a dry run takes much longer.
Step 1: markers
grep -rnE '^(<<<<<<<|=======|>>>>>>>|\|\|\|\|\|\|\|)' force-appNo output means no marker lines remain. Anchoring the pattern to the start of the line avoids false hits on values that contain those characters.
Step 2: well-formedness
xmllint --noout force-app/main/default/permissionsets/Sales_Access.permissionset-meta.xmlxmllint prints nothing on success and gives a line and column on failure. To check every file Git still lists as touched by the merge, loop over them:
git diff --name-only HEAD | grep -E '\-meta\.xml$' | while read -r f; do
xmllint --noout "$f" || echo "FAILED: $f"
doneStep 3: duplicates
xmllint cannot tell you that a field appears twice. A short script can for the entry types you care about. This one checks fieldPermissions in permission sets and profiles:
import sys
import xml.etree.ElementTree as ET
from collections import Counter
NS = "{http://soap.sforce.com/2006/04/metadata}"
def check(path):
try:
root = ET.parse(path).getroot()
except ET.ParseError as err:
print(f"{path}: not well-formed: {err}")
return False
fields = Counter(
el.findtext(f"{NS}field") for el in root.findall(f"{NS}fieldPermissions")
)
duplicates = [name for name, count in fields.items() if count > 1]
for name in duplicates:
print(f"{path}: duplicate fieldPermissions for {name}")
return not duplicates
if __name__ == "__main__":
results = [check(p) for p in sys.argv[1:]]
sys.exit(0 if all(results) else 1)Save it as check_metadata.py and run it with python3 check_metadata.py force-app/main/default/permissionsets/*.xml. The exit code is 1 when a file fails, so you can reuse it in CI later. Extend the Counter approach to other repeating elements such as classAccesses (keyed on apexClass).
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Parser error at a `<<<<<<<` or `=======` line | Marker line left in the file | Delete the marker lines |
| Mismatched or unexpected closing tag | Block resolved half way | Restore the whole element from one side |
| "Entity ... not defined" or similar error on a value | Unescaped `&` | Use `&` |
| Deployment error about duplicate values | Both sides added the same item | Keep one entry and merge its settings |
| Whole file shows as changed in the next diff | Editor changed line endings or indentation | Restore LF and four spaces |
Exercise
After keeping both sides of a conflict in a permission set, xmllint --noout prints nothing and no marker lines remain. Why can you still not commit yet, and what two kinds of problem might remain?
Show answer
xmllint only proves the file is well-formed. Duplicate entries may remain, for example two fieldPermissions blocks for the same field when both branches granted access to it. Values may also be wrong, for example when you kept the wrong setting in a competing edit. Neither shows up in a parse. Run a duplicate check, then a deployment dry run against a sandbox, before you stage and commit.