Way to escape XML?

Sunday, 24 March 2019 · 3 messages
AM
Andreas Mixich24 Mar 2019 04:22 #
Hi, I must be missing the obvious, but is there a way to serialize element() or node() into xs:string with the XML getting entity escaped in BaseX? Something like:
let $xml as element() := <xml>Hello World</xml>
return serialize($xml, map{"method":"entity-escaped-string"}
would result in &lt;xml&gt;Hello World&lt;/xml&gt;
-- Goody Bye, Minden jót, Mit freundlichen Grüßen, Andreas Mixich
LQ
Liam R. E. Quin24 Mar 2019 07:48 #
Quoted text · Andreas Mixich · 7 lines
On Sun, 2019-03-24 at 04:22 +0100, Andreas Mixich wrote: > let $xml as element() := <xml>Hello World</xml> > return serialize($xml, map{"method":"entity-escaped-string"} > > would result in > > &lt;xml&gt;Hello World&lt;/xml&gt;
One way,
declare function local:escapexml($input as item()*) as xs:string?
{
  <wrapper>{fn:serialize($input)}</wrapper>/text()
};

declare option output:method   "xml";

local:escapexml(
  <boy>
    <name>Simon</name>
    <age>24 years</age>
    <socks>blue</socks>
  </boy>
)
Note that if you don’t have the XML output method, strings are output without escaping, so you can’t see that it has worked. Liam
-- Liam Quin, https://www.delightfulcomputing.com/ Available for XML/Document/Information Architecture/XSLT/ XSL/XQuery/Web/Text Processing/A11Y training, work & consulting. Web slave for vintage clipart http://www.fromoldbooks.org/
AM
Andreas Mixich24 Mar 2019 10:13 #
Quoted text · Liam R. E. Quin · 3 lines
Am 24.03.2019 um 06:47 schrieb Liam R. E. Quin: > Note that if you don’t have the XML output method, strings are output > without escaping, so you can’t see that it has worked.
Interesting, indeed. I wonder whether it wouldn't make sense, to have BaseX provide escape()/unescape() shortcut functions, maybe in the conversion module. For now, I found a way to circumvent the global setting by adding an addition fn:serialize#1 function call:
  declare function local:escapexml($input as item()*) as xs:string?
  {
    serialize(<wrapper>{fn:serialize($input)}</wrapper>/text(),map{"method":"xml"})
  };
Thanks for helping out!
-- Goody Bye, Minden jót, Mit freundlichen Grüßen, Andreas Mixich

⚡Generated with XQuery