Bash: Escape Xml
Appearance
Problem
When building XML with bash, special XML characters need to be escaped.
Solution
# Escape XML characters for use in text
# @param $1 Text to escape for XML
# @output XML escaped text
# See: https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents
function escape_xml_text() {
local ret=$1
ret=${ret//&/&}
ret=${ret//</<}
ret=${ret//>/>}
printf %s "$ret"
}
# Escape XML characters for use in attributes
# @param $1 Text to escape for XML
# @output XML escaped text
# See: https://stackoverflow.com/questions/1091945/what-characters-do-i-need-to-escape-in-xml-documents
function escape_xml_attribute() {
local ret=$1
ret=${ret//&/&}
ret=${ret//</<}
ret=${ret//>/>}
ret=${ret//'"'/"e;}
ret=${ret//"'"/'}
printf "%s" "$ret"
}Usage:
text=$'\'"&<>' cat << XML <foo bar="$(escape_xml_attribute "$text")">$(escape_xml_text "$text")</foo> XML
Returns:
<foo bar="'"e;&<>">'"&<></foo>