Home > front end >  How to convert xml to hashmap and ignore empty tags in Kotlin
How to convert xml to hashmap and ignore empty tags in Kotlin

Time:02-08

I want to convert an xml value to a map, but empty tags also come into the map. I don't want empty tags. maybe a has nested nodes. See below for an example

a = "<rootTag><name>Ali Tan</name><address><tag1>aaa</tag1><tag2></tag2></address></rootTag>"

  @Test
fun contextLoads() {
    var a = "<rootTag><name>Ali Tan</name><address></address></rootTag>"
    val xmlMapper = XmlMapper()
    val aa = xmlMapper.readValue(a, HashMap::class.java)
    println(aa)

}

code result:

{address=, name=Ali Tan}

i want to see

{name=Ali Tan}

CodePudding user response:

Just filter out empty values afterward:

val aa = xmlMapper.readValue(a, HashMap::class.java).filterValues { it.isNotEmpty() })

CodePudding user response:

If you want to delete all empty tags, you can do it using reccursion:

fun deleteAllEmptyTags(map: Map<*, *>): Map<*, *> {
    return map
        .mapValues { (_, value) ->
            when (value) {
                is Map<*, *> -> deleteAllEmptyTags(value)
                else -> value
            }
        }
        .filterValues {
            when (it) {
                is Map<*, *> -> it.isNotEmpty()
                is String -> it.isNotBlank()
                else -> true
            }
        }
}

For every value in map that is also a map we recursively delete all its tags. After that we filter out empty maps and blank strings.

It even should work with clearing tags that contain only empty tags

Example

<rootTag><name>Ali Tan</name><address></address><outer><inner></inner></outer></rootTag>

Result before deleting

{address=, name=Ali Tan, outer={inner=}}

Result after deleting

{name=Ali Tan}

  •  Tags:  
  • Related