How to get size of XML message payload in KB using dataweave

382 Views Asked by At

I have a requirement to calculate the size of incoming payload in KB. The incoming payload is an XML. I tried using sizeOf(payload.^raw)/1000 but this only works for JSON format and not XML format.

2

There are 2 best solutions below

2
Harsha Shivamurthy On

In this example, xmlPayload represents your incoming XML payload. We use the write function to convert the XML payload to a string in XML format (application/xml). Then, we calculate the size of the string using sizeOf and divide it by 1000 to get the size in kilobytes (KB).

You can replace xmlPayload with your actual XML payload, and the result will be the size of the payload in KB.

%dw 2.0
output application/json

var xmlPayload = "<root><element1>Value 1</element1><element2>Value 2</element2></root>"

var xmlString = write(payload, "application/xml")
var sizeInKB = sizeOf(xmlString) / 1000

---
{
  "sizeInKB": sizeInKB
}
2
aled On

You can not measure the input directly because it is already parsed into DataWeave objects that represent the original XML input. You can is to convert that object to an XML string and then convert the string to a Binary so you use the sizeOf() function to measure the number of bytes. Otherwise if using it on a string it will return the number of characters, which is not exactly the same. In Unicode there are multibyte characters which count as 1 character but take more than 1 byte to represent.

There is a caveat that the size will be calculated from the output of the write() function which will transform the data and add indentation and change some things of the structure, so it may not be exactly the same as the input.

%dw 2.0
output application/java

var someXml = read("<root><element1>Value 1</element1><element2>あ</element2></root>", "application/xml")

fun sizeInBytes(xml)=sizeOf(write(xml,"application/xml") as Binary)
fun sizeInKB(xml)=sizeInBytes(xml)/1024

---
{
    sizeOf: sizeOf(write(someXml,"application/xml")),
    sizeInBytes: sizeInBytes(someXml),
    sizeInKB: sizeInKB(someXml)
}

Output:

{sizeOf=109, sizeInBytes=111, sizeInKB=0.1083984375}