fn:parse-xml vs fn:parse-xml-fragment in XPath 3.0
XPath 3.0 introduces both fn:parse-xml and
fn:parse-xml-fragment to convert string data into XML node
trees directly within queries. While both functions parse serialized XML
markup into an XDM (XPath and XQuery Data Model) document node, they
differ fundamentally in the structural validity they require from the
input string, how they handle top-level nodes, and their tolerance for
empty or partial XML content.
Input Conformance and Well-Formedness
fn:parse-xml($arg)expects a fully well-formed XML document adhering to thedocumentproduction rule of the XML specification. The input must contain exactly one top-level root element (ignoring comments and processing instructions) and can include an XML declaration or DOCTYPE declaration.fn:parse-xml-fragment($arg)parses the input as an XML external general parsed entity. It does not require a single root element and can parse arbitrary chunks of XML markup, such as sequences of sibling elements, loose text nodes, or mixed content.
Top-Level Content Structure
fn:parse-xml()returns a document node containing exactly one element child node, alongside any valid top-level comments or processing instructions. Top-level text nodes (other than whitespace outside the root element) cause a dynamic error.fn:parse-xml-fragment()returns a document node that can contain any sequence of nodes as children, including multiple elements, interspersed text nodes, comments, and processing instructions.
Handling Empty Strings
fn:parse-xml("")raises a dynamic error (err:FODC0006) because an empty string is not a well-formed XML document.fn:parse-xml-fragment("")succeeds and returns an empty document node containing no child nodes.
Declarations and DTDs
fn:parse-xml()permits a<!DOCTYPE ...>declaration in the input string, allowing entity references defined in an internal DTD subset to be resolved.fn:parse-xml-fragment()does not allow<!DOCTYPE ...>declarations. Using a DOCTYPE declaration inside a fragment string results in a parsing error.
Summary of Use Cases
Use fn:parse-xml() when you are processing complete,
standalone XML documents where standard XML document rules must be
strictly enforced. Use fn:parse-xml-fragment() when dealing
with partial XML payloads, template snippets, multiple adjacent sibling
elements, or strings that contain unwrapped text mixed with inline
markup.