lib: add function escapeXML

Given a string, this function returns a string that can be inserted
verbatim in an XML document.
main
Robert Helgesson 3 years ago
parent a7eb89bdba
commit e75f346aa3
No known key found for this signature in database
GPG Key ID: 36BDAA14C2797E89
  1. 2
      lib/default.nix
  2. 13
      lib/strings.nix
  3. 5
      lib/tests/misc.nix

@ -91,7 +91,7 @@ let
concatImapStringsSep makeSearchPath makeSearchPathOutput
makeLibraryPath makeBinPath optionalString
hasInfix hasPrefix hasSuffix stringToCharacters stringAsChars escape
escapeShellArg escapeShellArgs escapeRegex replaceChars lowerChars
escapeShellArg escapeShellArgs escapeRegex escapeXML replaceChars lowerChars
upperChars toLower toUpper addContextFrom splitString
removePrefix removeSuffix versionOlder versionAtLeast
getName getVersion

@ -362,6 +362,19 @@ rec {
if match "[a-zA-Z_][a-zA-Z0-9_'-]*" s != null
then s else escapeNixString s;
/* Escapes a string such that it is safe to include verbatim in an XML
document.
Type: string -> string
Example:
escapeXML ''"test" 'test' < & >''
=> "\\[\\^a-z]\\*"
*/
escapeXML = builtins.replaceStrings
["\"" "'" "<" ">" "&"]
["&quot;" "&apos;" "&lt;" "&gt;" "&amp;"];
# Obsolete - use replaceStrings instead.
replaceChars = builtins.replaceStrings or (
del: new: s:

@ -246,6 +246,11 @@ runTests {
};
};
testEscapeXML = {
expr = escapeXML ''"test" 'test' < & >'';
expected = "&quot;test&quot; &apos;test&apos; &lt; &amp; &gt;";
};
# LISTS
testFilter = {

Loading…
Cancel
Save