OPENXML UDF
Description
This custom UDF is added to process a rowset view over an XML document. This would be used for declarations in because it works as a rowset provider.
Optional parameters and different node types are not supported in this version of the UDF. The element node is processed by default.
Custom UDF overloads
Parameters
XML: A
VARCHARthat represents the readable content of the XML.PATH: A varchar that contains the pattern of the nodes to be processed as rows.
CREATE OR REPLACE FUNCTION OPENXML_UDF(XML VARCHAR, PATH VARCHAR) RETURNS TABLE(VALUE VARIANT) LANGUAGE SQL AS
$$
SELECT VALUE from TABLE(FLATTEN(input=>XML_JSON_SIMPLE(PARSE_XML(XML)), path=>PATH))
$$;
CREATE OR REPLACE FUNCTION XML_JSON_SIMPLE(XML VARIANT) RETURNS OBJECT LANGUAGE JAVASCRIPT AS
$$
function toNormalJSON(xmlJSON) {
var finalres = {};
var name=xmlJSON['@'];
var res = {};
finalres[name] = res;
for(var key in xmlJSON)
{
if (key == "@")
{
res["$name"] = xmlJSON["@"];
}
else if (key == "$") {
continue;
}
else if (key.startsWith("@"))
{
res[key]=xmlJSON[key];
}
else
{
var elements = xmlJSON['$']
var value = xmlJSON[key];
res[key] = [];
if (Array.isArray(value))
{
for(var elementKey in value)
{
var currentElement = elements[elementKey];
var fixedElement = toNormalJSON(currentElement);
res[key].push(fixedElement);
}
}
else if (value === 0)
{
var fixedElement = toNormalJSON(elements);
res[key].push(fixedElement);
}
}
}
return finalres;
}
return toNormalJSON(XML);
$$SQL Server
Snowflake
Related EWIs
MSCEWI1020: CUSTOM UDF INSERTED.
MSCEW4067: INVALID PARAMETERS IN OPENXML.
Last updated
Was this helpful?