Escape special path characters for XML string

I'm using this AppleScript to generate Macros but sometimes because paths contain some special characters it breaks the XML output.
So far I've been able to correct only the "&" character. I'd like to have a solution that covers every case that might break this code.

tell application "Keyboard Maestro Engine"
	set location to value of variable "CurrentTempPath"
	set macroname to value of variable "CurrentTempPathMacroName"
end tell

-- Escape & character in the location variable
set escapedLocation to do shell script "echo " & quoted form of location & " | sed 's/&/&/g'"

set axml to "<dict>
						<key>Action</key>
						<string>ByTyping</string>
						<key>MacroActionType</key>
						<string>Open1File</string>
						<key>Path</key>
						<string>" & escapedLocation & "</string>
					</dict>"

tell application "Keyboard Maestro"
	tell macro group "Temporary Project Locations"
		set m to make new macro with properties {name:macroname}
		tell m to make new action with properties {xml:axml}
	end tell
end tell
""

Try using a KM "Filter: Encode HTML entities -- to source" action on CurrentTempPath before you use it in the AppleScript. That'll encode any of <>&", and you don't need to encode ' because you are using double-quotes as your XML string delimiters.

1 Like