diff --git a/contrib/xml2/expected/xml2.out b/contrib/xml2/expected/xml2.out
index eba6ae60364..3027e4df868 100644
--- a/contrib/xml2/expected/xml2.out
+++ b/contrib/xml2/expected/xml2.out
@@ -222,3 +222,13 @@ $$
$$);
ERROR: failed to apply stylesheet
+-- empty output
+select xslt_process('',
+$$
+$$);
+ xslt_process
+--------------
+
+(1 row)
+
diff --git a/contrib/xml2/expected/xml2_1.out b/contrib/xml2/expected/xml2_1.out
index bac90e5a2a9..ed3e399aa31 100644
--- a/contrib/xml2/expected/xml2_1.out
+++ b/contrib/xml2/expected/xml2_1.out
@@ -166,3 +166,9 @@ $$
$$);
ERROR: xslt_process() is not available without libxslt
+-- empty output
+select xslt_process('',
+$$
+$$);
+ERROR: xslt_process() is not available without libxslt
diff --git a/contrib/xml2/sql/xml2.sql b/contrib/xml2/sql/xml2.sql
index ac49cfa7c52..c7fe0c102da 100644
--- a/contrib/xml2/sql/xml2.sql
+++ b/contrib/xml2/sql/xml2.sql
@@ -137,3 +137,9 @@ $$
$$);
+
+-- empty output
+select xslt_process('',
+$$
+$$);
diff --git a/contrib/xml2/xslt_proc.c b/contrib/xml2/xslt_proc.c
index f30a3a42c03..9f3bf527d80 100644
--- a/contrib/xml2/xslt_proc.c
+++ b/contrib/xml2/xslt_proc.c
@@ -179,7 +179,14 @@ xslt_process(PG_FUNCTION_ARGS)
if (resstat < 0)
PG_RETURN_NULL();
- result = cstring_to_text_with_len((char *) resstr, reslen);
+ /*
+ * If an empty string has been returned, resstr would be NULL. In
+ * this case, assume that the result is an empty string.
+ */
+ if (reslen == 0)
+ result = cstring_to_text("");
+ else
+ result = cstring_to_text_with_len((char *) resstr, reslen);
if (resstr)
xmlFree(resstr);