- Categories:
Conversion functions , Semi-structured and structured data functions (Cast)
TO_XML¶
Converts a VARIANT to a VARCHAR that contains an XML representation of the value. If the input is NULL, the result is also NULL.
Syntax¶
Arguments¶
expressionAn expression that evaluates to a VARIANT or that can be cast to a VARIANT.
Returns¶
The data type of the returned value is VARCHAR.
Usage notes¶
Common uses for this function include:
Generating a string that contains an XML-formatted value that matches an originally inserted XML-formatted value.
Converting a semi-structured value (which doesn’t necessarily need to have been formatted as XML originally) into an XML-formatted value. For example, you can use TO_XML to generate an XML-compatible representation of a value that was originally formatted as JSON.
If the input
expressiondoesn’t evaluate to a VARIANT, Snowflake implicitly casts the result of the expression to a VARIANT. Because all other Snowflake data types can be cast to VARIANT, this means that a value of any data type can be passed to TO_XML and converted to an XML-formatted string. (The GEOGRAPHY data type is a partial exception; to call TO_XML with a value of type GEOGRAPHY, you must explicitly cast the GEOGRAPHY value to VARIANT.)If the value didn’t originate as XML, then Snowflake generates XML-compatible tags. These tags may use the
typeattribute to specify the Snowflake data type of the tag’s contents. Below are examples of tags generated by Snowflake.The outermost tag pair is similar to the following:
The data type specified in the
typeattribute of the tag can vary.For an OBJECT, each key-value pair’s tags are based on the key. For example:
For an ARRAY, each element of the array is in a tag pair similar to:
Here is a complete example of the XML for a simple OBJECT that contains two key-value pairs:
Here is a complete example of the XML for a simple ARRAY that contains two VARCHAR values:
Examples¶
This example shows how to use the function if you’ve loaded XML-formatted data into an OBJECT by calling PARSE_XML.
Create a table and insert data:
Call the TO_XML and TO_VARCHAR functions:
You can also call the TO_XML function with data that did not originate as XML-formatted data, as shown in the examples below.
The following example creates a simple OBJECT and then generates the corresponding XML. The XML output contains information about the data types of the values in the key-value pairs, as well as the data type of the overall value (OBJECT).
The following example creates a simple ARRAY and then generates the corresponding XML. The XML output contains information about the data types of the array elements, as well as the data type of the overall value (ARRAY).
The following example inserts data that is in JSON format and then generates the corresponding XML.