Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MarkLogic XML to JSON conversion

Tags:

marklogic

I am trying to convert this XML file into JSON but unable to get any success. I have two child element in my XML but it is returning only last one. How to get both the records in JSON format?

XML

 <Carousel>
  <Video>
    <Title>1</Title>
    <Abstract>3</Abstract>
    <FileName type="custom" mediatype="image">D</FileName>
    <HasAccess>4</HasAccess>
  </Video>
  <Video>
    <Title>1</Title>
    <Abstract>2</Abstract>
    <FileName type="custom" mediatype="image">D</FileName>
    <HasAccess>3</HasAccess>
  </Video>
</Carousel>

XQUERY:

import module namespace json = "http://marklogic.com/xdmp/json"  at "/MarkLogic/json/json.xqy";

let $custom := let $config := json:config("custom")
           return 
             (
              map:put( $config, "whitespace", "ignore" ),

              $config
             )
let $XML := $XMLFile (: XML content :)
return json:transform-to-json($XML,$custom)

Current OUTPUT:

{"Carousel":{"Video":{"Title":"1", "Abstract":"2", "FileName":{"type":"custom", "mediatype":"image", "_value":"D"}, "HasAccess":"3"}}}

I also tried it with default "Basic" JSON setting json:transform-to-json($XML) but got error like

XML Element not in expected namespace [http://marklogic.com/xdmp/json/basic] (json:INVALIDELEM): Carousel

It works in "Full" mode only, but it is adding some extra information in JSON format like _attribute etc. which is not required in my output JSON.

Please help me or give any idea why it is not returning complete output in JSON format.

like image 902
Navin Rawat Avatar asked Dec 03 '25 17:12

Navin Rawat


1 Answers

You will need to mark repeating elements as array-elements for starters. This seems to work:

xquery version "1.0-ml";

import module namespace json = "http://marklogic.com/xdmp/json" at "/MarkLogic/json/json.xqy";

let $xml := <Carousel>
  <Video>
    <Title>1</Title>
    <Abstract>3</Abstract>
    <FileName type="custom" mediatype="image">D</FileName>
    <HasAccess>4</HasAccess>
  </Video>
  <Video>
    <Title>1</Title>
    <Abstract>2</Abstract>
    <FileName type="custom" mediatype="image">D</FileName>
    <HasAccess>3</HasAccess>
  </Video>
</Carousel>

let $custom :=
  let $config := json:config("custom")
  let $_ := map:put( $config, "whitespace", "ignore" )
  let $_ := map:put( $config, "array-element-names", "Video" )
  return $config

return json:transform-to-json($xml,$custom)

You can probably also suppress attributes if you like. The config supports all kinds of options, I recommend looking at its documentation:

http://docs.marklogic.com/json:config

HTH!

like image 143
grtjn Avatar answered Dec 06 '25 10:12

grtjn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!