Support Questions

Find answers, ask questions, and share your expertise
Announcements
Celebrating as our community reaches 100,000 members! Thank you!

Attributes to XML (not JSON)

avatar
Rising Star

Im looking for a way to get attributes in an XML file instead of json. The current proccesor only does attributes to json.

Any ideas? Maybe using an execute script proccesor? Lua code?

Thank you!

1 ACCEPTED SOLUTION

avatar
Master Guru

Yes it is possible with ExecuteScript if nothing else. Try the following Groovy script in your ExecuteScript processor:

def flowFile = session.get()
if(!flowFile) return
class WriteCallback implements OutputStreamCallback {
  Map attrs
  WriteCallback(attributes) {
    attrs = attributes
  }
  void process(OutputStream outputStream) {
    outputStream.write('<root>\n'.bytes)
    attrs.each {k,v -> 
      outputStream.write("<property>\n\t<name>$k</name>\n\t<value>$v</value>\n".bytes)
    }
    outputStream.write('</root>'.bytes)
  }
}
def wb = new WriteCallback(flowFile.attributes)
flowFile = session.write(flowFile, wb)
flowFile = session.putAttribute(flowFile, org.apache.nifi.flowfile.attributes.CoreAttributes.MIME_TYPE.key(), 'application/xml')
session.transfer(flowFile, REL_SUCCESS)

This should pretty-print your attributes in a "properties-style" XML format. Of course you can edit the script to give you the schema you like.

View solution in original post

2 REPLIES 2

avatar
Master Guru

Yes it is possible with ExecuteScript if nothing else. Try the following Groovy script in your ExecuteScript processor:

def flowFile = session.get()
if(!flowFile) return
class WriteCallback implements OutputStreamCallback {
  Map attrs
  WriteCallback(attributes) {
    attrs = attributes
  }
  void process(OutputStream outputStream) {
    outputStream.write('<root>\n'.bytes)
    attrs.each {k,v -> 
      outputStream.write("<property>\n\t<name>$k</name>\n\t<value>$v</value>\n".bytes)
    }
    outputStream.write('</root>'.bytes)
  }
}
def wb = new WriteCallback(flowFile.attributes)
flowFile = session.write(flowFile, wb)
flowFile = session.putAttribute(flowFile, org.apache.nifi.flowfile.attributes.CoreAttributes.MIME_TYPE.key(), 'application/xml')
session.transfer(flowFile, REL_SUCCESS)

This should pretty-print your attributes in a "properties-style" XML format. Of course you can edit the script to give you the schema you like.

avatar
Explorer

I am looking for a way to convert DB Query reusult set to XML and XML to SQL and also JSON to XML. Is this doable?