Transform XML to JSON wit xQuery in BaseX for use as a D3 tree.

Friday, January 29th, 2016 | Author:

Currently working with XML structured legal texts, I often need to transform them  into a JSON format compatible with D3 tree visualisation. BaseX is a great app, but its code documentation isn’t exactly user-friendly.

Here I want to transform a document srutured as

<text>
 <meta></meta>
 <doc>
 <p>
 <s>
 <t></t>
 </s>
 </p>
 </doc>
</text>

And here is the code to do the XML to D3 JSON transform:

 

declare option output:method "json";
 
declare function local:children($a) {
  for $b in $a/*
  return (
    <name>{node-name($b)}</name>,
    if (count($b/*) > 0)
    then
    <children type="array"><_ type="object">{local:children($b)}</_></children>
    else()
  )
};
 
  <json type="object">{
      for $x in doc("db/path/to/doc.xml")//doc
      return (
        <name>{//meta/name/text()}</name>,
        <v type="number">count($x/*)</v>,
        if (count($x/*) > 0)
        then <children type="array"><_ type="object">{local:children($x)}</_></children>
        else ()      
      )
    }</json>
Cite as: André Ourednik (2016) « Transform XML to JSON wit xQuery in BaseX for use as a D3 tree. » in Maps and Spaces from https://ourednik.info/maps/2016/01/29/xml-to-json-in-basex-for-d3-tree/ [Last-seen December 11th 2017].