Bash: Escape Xml

From FVue
Jump to: navigation, search

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//</&lt;}
    ret=${ret//>/&gt;}
    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//&/&amp;}
    ret=${ret//</&lt;}
    ret=${ret//>/&gt;}
    ret=${ret//'"'/&quote;}
    ret=${ret//"'"/&apos;}
    printf "%s" "$ret"
}

Usage:

text=$'\'"&<>'
cat << XML
<foo bar="$(escape_xml_attribute "$text")">$(escape_xml_text "$text")</foo>
XML

Returns:

<foo bar="&apos;&quote;&amp;&lt;&gt;">'"&amp;&lt;&gt;</foo>