Transform XML into a Map using groovy

2019-06-11 12:45发布

问题:

I have some XML that I want to transform into a Map. I used the middle way of transforming XML to JSON and then greating a map of the json:

import org.json.XML
import groovy.json.JsonSlurper
  Map parseXml(String input) {
    String json = XML.toJSONObject(input).toString()
    new JsonSlurper().parseText(json)
  }

But when you have name spacing, it does not get removed.

eg.

<ns2:someObject xmlns:ns2="http://someLink">
  <someOtherObject>
    <something>SOME_THING</something>
  </someOtherObject>
  <someOtherObject>
    <something>SOME_THING_ELSE</something>
  </someOtherObject>
</ns2:someObject>

will end up in

{
  "ns2:someObject": {
    "xmlns:ns2": "http://someLink",
    "someOtherObject": [
      {
        "something": "SOME_THING"
      },
      {
        "something": "SOME_THING_ELSE"
      }
    ]
  }
}

But I want it to end up like this:

{
  "someObject":  [
      {
        "something": "SOME_THING"
      },
      {
        "something": "SOME_THING_ELSE"
      }
    ]
}

Does anyone have an idea how I can achive that without reinventing the wheel?

I already found a post a bit similar to mine, but it has a different approach, that's why I asked my question. The example I gave is just an example, but there dan be multiple entries of someObjects which the given answer in the other post does not include. Secondly it does iterate over the XML and creates a map of it - that is what I meant with reinventing the wheel. I am sure there must be a library doing exactly that already, so for me it seems wrong to write the parsing code myself.

Many thanks