Search code examples
xquerymarklogic

Xquery - Using sparql results to dynamically create XML. Dynamic Element Names


I am using MarkLogic 8.

I have a SPARQL statement as such.

let $results :=
  sem:sparql(
  "
    PREFIX  skosxl: <http://www.w3.org/2008/05/skos-xl#>
        PREFIX  rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        PREFIX  owl:  <http://www.w3.org/2002/07/owl#>
        PREFIX  skos: <http://www.w3.org/2004/02/skos/core#>
        PREFIX  rdfs: <http://www.w3.org/2000/01/rdf-schema#>
        PREFIX slc: <http://www.smartlogic.com/2014/08/semaphore-core#>

  select  ?relation ?value
  where 
  {
  $input ?relation ?c .
  OPTIONAL {  
    ?c skosxl:prefLabel/skosxl:literalForm|skosxl:literalForm ?d .
  }
      BIND ( if (bound(?d), ?d, ?c) as ?value )
  } 
  ", $bindings
  )

This gives me back results that are a list of (relation, value) pairs.

I am trying to turn this response into an XML document that will be stored statically.

I've tried a variety of different approaches.

Attempt 1

let $doc :=  <test>{
  for $item in $results 
    return element {map:get($item, 'relation')} {map:get($item, 'value')}
    }</test>

 return $doc

Error :

XDMP-ELEMNAME: (err:XPTY0004) for $item in $results -- Cannot use sem:iri("http://www.w3.org/2008/05/skos-xl#altLabel") as an element name

I tried casting the item in question, to a string using fn:string but that leads to a

[1.0-ml] XDMP-QNAMELEXFORM: for $item in $results -- Invalid lexical form for QName

How can i declare a dynamic element name in XQuery during XML Building? What is causing this error in the first place? I have been messing with syntax to try and figure it out, what am I unaware of that is causing this issue?

Thank you for reading.


Solution

  • Casting as string should be enough.

    However, your example has foreward slashes which I believe are invalid.

    Second, your example would be making an element defined as being in the html namespace - or whatever you defined the prefix html to be.

    Also, the first char after the colon is not an alphanumeric characters which is required.

    In my opinion, the name you are trying to use for an element name is the issue - not the actual approach.