Search code examples
xquerymarklogic

Converting string to element in Marklogic Xquery


I have the following XQuery script that basically adds properties to an existing document in MarkLogic:

xquery version "1.0-ml";
declare namespace xhtml = "http://www.w3.org/1999/xhtml";
declare namespace error="http://marklogic.com/xdmp/error";
declare namespace cdata = "http://www.w3.org/1999/cdata";

declare variable $uri as xs:string external;
declare variable $contentproperties as xs:string external;

xdmp:document-add-properties($uri, ( $contentproperties ) );

The external C# program calls this query and passes in the following as string for the $contentproperties:

<Title>My Title</Title>,<Date>1629076218</Date>,<SubjectArea>My subject</SubjectArea>,<ContentType>My content type</ContentType>,<Summary>My summary</Summary>

However, an error returns mentioning that:

XDMP-ARGTYPE: (err:XPTY0004) xdmp:document-add-properties("", "My Title,1629076218,My ...") -- arg2 is not of type element()*"

How should I convert xs:string to element()* type?

Reference to the document-add-properties method: https://docs.marklogic.com/xdmp:document-add-properties


Solution

  • You can tokenize() that string of comma separated values, then use xdmp:unquote() to parse the XML string into an XML document, and then XPath to the element. Assign that sequence of elements to another variable, and use that variable to set your properties:

    xquery version "1.0-ml";
    declare namespace xhtml = "http://www.w3.org/1999/xhtml";
    declare namespace error="http://marklogic.com/xdmp/error";
    declare namespace cdata = "http://www.w3.org/1999/cdata";
    
    declare variable $uri as xs:string external := "test";
    declare variable $contentproperties as xs:string external := "<Title>My Title</Title>,<Date>1629076218</Date>,<SubjectArea>My subject</SubjectArea>,<ContentType>My content type</ContentType>,<Summary>My summary</Summary>";
    declare variable $contentproperties-element as element()* := tokenize($contentproperties, ",") ! xdmp:unquote(.)/*;
    xdmp:document-add-properties($uri, ( $contentproperties-element ) );