Search code examples
xmlxquery

Use fn:parse-xml() in xquery conditionally on whether output is well formed


I'm writing an xquery in which I'm passing some markup, which was captured in CDATA within a particular element in the XML source, through to an output XML document as a mixed-content element. Most of the time, the result of fn:parse-xml($input) is well-formed XML. However, sometimes the markup is faulty, and if there is any such instance anywhere in the whole input document, that one instance of fn:parse-xml() fails, and so the whole query fails.

Is there any way to configure a variable such that if the output of fn:parse-xml($input) is well-formed XML it returns the output, but if it is not then it returns an alternative, such as an empty sequence or boilerplate text like "The source is not well formed"?


Solution

  • Sure, use try {parse-xml($input)} catch * {()} - or you can be more selective about which errors to catch if you wish.