redundent / kotlin-xml-builder

A lightweight type safe builder to build xml documents in Kotlin
Apache License 2.0
151 stars 17 forks source link

How to insert node within Node via DSL #58

Closed levinotik closed 9 months ago

levinotik commented 10 months ago

Firstly, thank you for this excellent library.

While this might not be a formal issue, I'm seeking guidance on a matter that involves nesting one XML node within another. Here's my scenario: I have a function that accepts an object that can be serialized to XML as an argument. Within this function, my objective is to create XML using the kotlin-xml-builder DSL (utilizing functions like xml(..)), and include the serialized object as part of the constructed XML. Currently, I've achieved this by using unsafeText, but I'm hopeful there might be a more elegant solution.

val requestCall: Node = xml("RequestCall") {
  encoding = "ISO-8859-1"
  version = XmlVersion.V10
  "RequestName" {
    -"User.Insert"
  }
  "Params" {
    // is there a better way to do this?
    unsafeText(xmlMapper.writeValueAsString(user))
  }
}

In the code snippet above, xmlMapper is an instance of com.fasterxml.jackson.dataformat.xml.XmlMapper, and writeValueAsString serializes the object into an XML string.

I'm curious if there's a recommended technique to accomplish this task. Specifically, I'm looking for a way to encapsulate existing XML within an outer XML document generated using DSL syntax.

Thanks in advance for the help!

redundent commented 9 months ago

I think your only options are to

  1. do it the way you have it now, which isn't great.
  2. use the various parse methods to take that string from your xmlMapper to parse it to a Node and then append it. It should work but it's not probably not the most efficient path since it requires serializing to a string just to parse it back to objects.
  3. build the user xml explicitly. I'm assuming this is a non-starter since it seems like you want it to be dynamic.

I haven't looked too much into jackson XmlMapper but I'm assuming it's similar enough to the json mapper. I can probably look into something to hook into jackson to more efficiently build a Node object from the mapper.

I'll keep you posted on that.

levinotik commented 9 months ago

@redundent thanks very much for the reply. Appreciate it!