Transform XML into a Map using groovy

陌路散爱 提交于 2020-01-25 08:12:24

问题


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

来源:https://stackoverflow.com/questions/51932850/transform-xml-into-a-map-using-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!