StatusAccepted
Discussion threadhttps://lists.apache.org/thread/fpzc746vn5ko0cn2g25hvtrfd6b038dj
Vote threadhttps://lists.apache.org/thread/fm69v3t73yhzjg9p4z19dd47ghvq4mfw
JIRA

FLINK-40805 - Getting issue details... STATUS

Release<Flink Version>

Motivation

Many users have XML in their data pipelines, but Flink SQL currently can't work with it natively. The only option today is a UDF with manual XML-parsing.

A semi-structured / VARIANT-like type is common across engines now. A built-in function to turn XML into that type is not. Only Snowflake and Databricks/Spark have it today.

This FLIP proposes to add three functions. PARSE_XML and TRY_PARSE_XML turn an XML string into a VARIANT, and XML_STRING turns a VARIANT back into an XML string. This mirrors the existing JSON functions PARSE_JSON, TRY_PARSE_JSON, and JSON_STRING.
Once XML is a VARIANT, you query it the same way as the output of PARSE_JSON: with the variant accessors (variant.key, variant['key'], variant[index]) and a CAST to the type you need.

Public Interfaces 

PARSE_XML(xml_string [, force_array])     → VARIANT   -- throws on invalid XML
TRY_PARSE_XML(xml_string [, force_array]) → VARIANT   -- returns NULL on invalid XML
XML_STRING(variant)                       → STRING    -- serializes a VARIANT back to XML

All three use normal function-call syntax. No new SQL grammar, Table API method, or Python API method is needed, same as PARSE_JSON.
PARSE_XML(NULL) and XML_STRING(NULL) return NULL. PARSE_XML is nullable only if its argument is. TRY_PARSE_XML is always nullable.

force_array is an optional boolean, default false. When true, every element maps to an array even if it appears once. See Element mapping.

Proposed Changes

Element mapping

  • An element with no attributes and no child elements becomes its value directly: the text content, or "" if there is no text.
    Example with text content: <title>Dune</title> → {"title": "Dune"}
    Example with empty text content: <title></title> → {"title": ""}

  • Otherwise it becomes an object. Each child element becomes a field named after its tag, each attribute becomes a @name field, and text goes into a $ field.

    Example with Child Element:
     

    <book>
      <title>Dune</title>
    </book>
    {
      "book": {
        "title": "Dune"
      }
    }

    Example with Attribute:
    <book pages="320">
     Dune
    </book>
    {
      "book": {
        "@pages": "320",
        "$": "Dune"
      }
    }
  • A tag that repeats among its siblings becomes an array. Repetition is the only way XML expresses a list. A tag that appears once stays a scalar or object, not a one-element array.

    Example with two child elements:

    <book>
      <author>Terry Pratchett</author>
      <author>Neil Gaiman</author>
    </book>
    {
      "book": {
        "author": ["Terry Pratchett", "Neil Gaiman"]
      }
    }
    Setting force_array to true overrides this: every element then maps to an array, so a tag has the same shape whether it appears once or many times. This is useful for streaming pipelines where the shape has to stay stable across records.

    Example with one child element and force_array=true:
    <book>
      <author>Terry Pratchett</author>
    </book>
    {
      "book": {
        "author": ["Terry Pratchett"]
      }
    }
  • A Variant object stores its fields sorted by key, not in document order. So an element with more than one distinct key among its children and text also gets a # field. It maps each key to the position(s) it had among the children and text runs, in document order. This is what lets us recover the order between differently-named siblings like <title> and <price>. With only one distinct key there is nothing to order — a single repeated tag already keeps its order in its array — so # is omitted.

    Example with sibling order tracking (#):

    <book>
      <title>Dune</title>
      <price>12.5</price>
    </book>
    {
      "book": {
        "#": { "price": 1, "title": 0 },
        "price": "12.5",
        "title": "Dune"
      }
    }
  • The field for storing text $ also becomes an array when text is split into several runs by child elements in between.

    Example with interleaved text runs:

    <book>
      This is a description
      <title>Dune</title>
      and this is another text
    </book>
    {
      "book": {
        "#": { "$": [0, 2], "title": 1 },
        "$": ["This is a description", "and this is another text"],
        "title": "Dune"
      }
    }

Full Example

<book pages="320">
  <title>Dune</title>
  This is a description
  <price>12.50</price>
  Text in between
  <price currency="EUR">13.50</price>
</book>
{
  "book": {
    "#": { "$": [1, 3], "price": [2, 4], "title": 0 }, 
    "$": ["This is a description", "Text in between"],
    "@pages": "320",
    "price": ["12.50", { "$": "13.50", "@currency": "EUR" }],
    "title": "Dune"
  }
}

Because @, $, and # are illegal initial characters for element and attribute names under the W3C XML specification, the metadata keys @attr, $, and # will never collide with mapped XML tag names.

Null and typed values via xsi:nil / xsi:type

XML documents are untyped text, so every value is a string by default. The only exception is explicit XML Schema instance annotations, which state the type instead of guessing it.

  • xsi:nil="true" makes the element a Variant null. This is different from the empty string you get from an empty element. The xsi:nil attribute itself is consumed, not kept as data.

  • xsi:type="<type>" stores the element's text as the matching Variant type. The value is matched by its local part, so xsi:type="int" and xsi:type="xs:int" are equivalent. The recognized XSD built-in types are:

    xsi:type
     

    Variant type
     

    string

    STRING

    boolean

    BOOLEAN

    byte

    TINYINT

    short

    SMALLINT

    int

    INT

    long

    BIGINT

    integer, decimal

    DECIMAL

    float

    FLOAT

    double

    DOUBLE

    date

    DATE

    time

    TIME

    dateTime

    TIMESTAMP, or TIMESTAMP_LTZ if the value carries a zone offset

Note: dateTime values keep nanosecond precision, time values keep microsecond precision.

The type attribute is consumed either way. Any other xsi:type (for example gYear, duration, or the unsigned and derived integer types such as unsignedInt and positiveInteger), and any value that does not parse as or does not fit the target type, falls back to STRING, so a bad annotation never fails the parse. XML_STRING writes the matching XSD name back (a TIMESTAMP as xsi:type="dateTime"), so a typed value it emits reads back to the same Variant type.

<a></a>                         → {"a": ""}
<a xsi:nil="true"/>             → {"a": null}
<a xsi:type="int">5</a>         → {"a": 5}
<a xsi:type="boolean">true</a>  → {"a": true}
<a xsi:type="decimal">-1.23</a> → {"a": -1.23} 

We match xsi:nil and xsi:type by the literal xsi: prefix, not by resolved namespace. The parser is not namespace-aware. This matches common XML tooling including Snowflake, and it has the same limitation, in both directions:
A different prefix bound to the XSD-instance namespace is not recognized. foo:nil with xmlns:foo="http://www.w3.org/2001/XMLSchema-instance" is read as a plain attribute, not a null.
A rebound xsi prefix is misread. By convention xsi maps to the XSD-instance namespace (http://www.w3.org/2001/XMLSchema-instance), and we rely on that convention. If you bind xsi to something else, you get wrong results. <a xmlns:xsi="urn:my-app" xsi:nil="true"/> is {urn:my-app}nil (an ordinary attribute) under namespace resolution, but we read xsi:nil as a null and drop the binding. It serializes back as <a xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>, so both the attribute's meaning and the namespace change. Correct handling needs namespace awareness (see Rejected Alternatives).

The Variant round-trip still holds either way: PARSE_XML(XML_STRING(v)) = v. Only the XML → Variant → XML direction is affected, which already produces a canonical form, not a byte copy.

XML_STRING (serialization)

Going from a Variant to XML and back is lossless: for any Variant v produced by PARSE_XML, PARSE_XML(XML_STRING(v)) = v.
Going the other way, from XML to a Variant and back — XML_STRING(PARSE_XML(x)) — is not lossless: parsing normalizes the document (see Normalizations), so the output is a canonical form of the input, not a byte copy. The type and nil information in the Variant drives how it is written back:

  • a Variant null becomes <name xsi:nil="true"/>. A plain <name/> would round-trip to "", not null.

  • a non-string scalar adds the type information back as attribute. E.g. for an int -> <a xsi:type="int">5</a>, so the Variant type survives.

  • an empty string becomes <name></name>, and a non-empty string becomes <name>text</name>.

  • the # field, if present, restores the document order of children and text, including mixed content (text between child elements).

  • When the output carries any xsi: attribute (xsi:nil or xsi:type), XML_STRING declares xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" on the root element, so the result is namespace-well-formed. Output with no xsi: attributes carries no such declaration.

Typed and nil values only come from xsi:type and xsi:nil in the input. So a document without those annotations gets none added. The output then matches the input except for the normalizations listed below. A Variant from a non-XML source like PARSE_JSON carries types that were never annotated. Whether XML_STRING should add xsi:type for those is a future option, and it doesn't affect the XML-to-Variant-to-XML round trip.

XML_STRING is defined only on Variants produced by PARSE_XML (objects using the @/$/# conventions). The no-collision guarantee for @/$/# holds for XML input, but XML_STRING accepts any Variant, so a Variant from another source can contain those keys as ordinary data. For example PARSE_JSON('{"#": {...}}') would have its # read as order metadata. Passing a non-PARSE_XML Variant to XML_STRING is out of contract and its result is undefined.

Normalizations

  • Comments and processing instructions carry no data and are dropped.

  • Namespace prefixes on element and attribute names are kept as-is in the key, not resolved.

  • The xmlns:xsi declaration is consumed by PARSE_XML and re-added by XML_STRING when the output uses xsi: attributes. Other namespace declarations (xmlns:foo) are kept as ordinary @xmlns:foo attributes.
  • Whitespace-only text nodes between element tags (e.g., formatting newlines and indentation) are trimmed by default.

  • Attributes are stored sorted by name, so their original order is not preserved. Child-element and text order is preserved, via #.

  • <a/> and <a></a> both map to "", so both are written back as <a></a>.

Security

XML input is untrusted, so the parser is configured to be safe against the common XML attacks:

A DTD (Document Type Definition) is an optional header in an XML document. Among other things it can define entities: named placeholders that expand into text when the document is parsed. An internal entity is defined inline in the document. An external entity points to an outside resource, a file path or a URL.

With that, the parser does three things:

  • Internal entities are expanded, so documents that use them parse instead of failing. This matches common tooling.

  • External entities and external DTDs are not resolved. This closes the XXE vector (XML External Entity), where an attacker points an entity at a local file or an internal URL to read files or make the server send requests on their behalf (the request part is SSRF, server-side request forgery).

  • Entity expansion is bounded, so a small input can't expand into a huge document. This is the billion laughs attack, where entities reference each other and expand exponentially. The bound comes from the parser's standard entity-expansion limit.

The functions are implemented as regular built-in scalar functions, like PARSE_JSON and JSON_STRING. No codegen or SQL-parser changes are needed.

Compatibility, Deprecation, and Migration Plan

This is purely additive. Three new functions, no changes to existing behavior, no deprecations. If we change the mapping later (for example honoring xml:space="preserve"), it will be a new opt-in parameter with the current default kept. The output shape described here is part of the functions' contract from the first release.

Test Plan

Unit tests for the mapping: element, attribute, and text handling, empty-to-"", xsi:nil-to-null, xsi:type typing and fallback, repeated-element arrays, the force_array option, the # field (present with more than one distinct key, omitted otherwise), mixed content, namespace prefixes, and CDATA. Security tests: internal entities are expanded, external entities and external DTDs are refused (including an XXE SYSTEM "file://…" payload), and a billion-laughs payload stays bounded. Round-trip tests that check PARSE_XML(XML_STRING(v)) equals v for representative Variants produced by PARSE_XML. Plus SQL and Table API integration tests for the functions end-to-end, including NULL handling and the PARSE_XML error path.

Rejected Alternatives

  • Common XML to JSON conversion:

    • JsonML: Lossless conversion of XML to JSON. Each element is a positional array [tag, attrs?, ...children].
      Book example from above in JsonML:

      ["book", {"pages": "320"},
        ["title", "Dune"],
        ["price", "12.50"],
        "Text in between",
        ["price", {"currency": "EUR"}, "13.50"]
      ]
      The VARIANT key access doesn't apply here, because the structure is positional, not keyed. To get the book title you'd write PARSE_XML(…)[3][2] (arrays are 1-based), which is not ergonomic and breaks if you add or reorder children.
    • BadgerFish: Name-keyed with @ attributes and $ text, very close to this proposal, but it has no way to recover sibling order. The # field is exactly what it is missing. We took its shape and added order recovery.

    • Snowflake: The element name is stored as a value under @, attributes are @name, and the content and child elements sit under $ as an ordered array. The ordered array keeps sibling order for free, but because the name is a value and not a key, you can't do a keyed lookup. To get the title you write GET(XMLGET(PARSE_XML(…), 'title'), '$'). That keyed access via .title is exactly what we want to keep.

    • Databricks: Very similar conversion to BadgerFish, which drops sibling order and is therefore unable to roundtrip back to the original XML.

  • Namespace-aware xsi: detection. Resolving prefixes to URIs would recognize xsi:nil and xsi:type no matter which prefix is used, which is correct per the spec. Rejected for now. It would require every prefix to be declared, so it would reject xsi:nil without an xmlns:xsi declaration. It also adds namespace resolution that the rest of the mapping avoids.

  • Always using arrays by default. Never collapsing a single occurrence to a scalar would be more uniform, but it is worse for the common case where an element appears once, and it makes paths longer (v.book.title[1] instead of v.book.title). We keep the scalar default and offer this behavior through the force_array parameter instead.

Future Work

  • Whitespace preservation for text runs, which are trimmed today. Either a preserve_whitespace opt-in for the whole document, or honoring xml:space="preserve" per subtree.

  • An XML_CHILD_AT(element, n) helper to get the n-th child regardless of tag, using the # field. This is the one query shape that name-keyed access can't express directly.

  • An option to control xsi:type output in XML_STRING. Today it always adds xsi:type for non-string scalars. An option could turn that off, for example for Variants that came from a non-XML source.