xmlxquery

How to parse from xml to json in xquery


i have an xml like this

<?xml version="1.0" encoding="UTF-8"?>
<groups>
  <group name="group1" location="city1">Group1</group>
  <group name="group2" location="city2">Group2</group>
</groups>

and i would like to parse it to a json string which has an output something like:

{
  "groups": [
    {
      "name": "group1",
      "location": "city1"
    },
    {
      "name": "group2",
      "location": "city2"
    }
  ]
}

I tried in my xql script the xml-to-json function with fn:xml-to-json(/xml) but did not success due to an exception: FOJS0006 xml-to-json: element found in wrong namespace: Could anyone give me a hint how can i parse the xml correctly to json? Thank you in advanced!

i tried to google and some suggestion but didn't success


Solution

  • XQuery 3.1 doesn't have a function that converts arbitrary XML to JSON (the xml-to-json function only handles a limited XML vocabulary - read the spec!).

    You need to do it by hand, for example

    map{"groups": array{
        for $gp in groups/group 
        return map{"name": $gp/@name,
                   "location": $gp/@location}
      }
    }
    

    And then to turn the tree of maps and arrays into lexical JSON, use the serialize() function with the JSON serialization method. You can also of course generate the lexical JSON "by hand" but getting the escaping and indentation right is tricky.