Skip to content

Allow naming of root element when rendering response as XML? #398

Description

@Ben-Fenner

We have a client who insists on our API providing XML, so we're fulfilling that.

The XML root element name is hard-coded to data in the Graphiti renderer which is not ideal since there is a child element inside also named data.
We have worked around this, but it would be nice to be able to specify the root element name where the Graphiti renderer could use it.

Looking at the source, here is where the magic happens, best I can tell:

render(self.class.hash_renderer(@proxy)).to_xml(root: :data)

Right now this is a simplified version of what our work-around looks like:

# app/controllers/api/my_controller.rb

class Api::MyController < Api::ApplicationController
  def index
    resources = MyResource.all(params)

    respond_to do |format|
      format.json    { render(json:    resources) }
      format.jsonapi { render(jsonapi: resources) }
      format.xml     { render(xml:     pretty_xml(resources)) }
    end
  end

  # By default when a Graphiti resource proxy list is resolved to XML it looks like this:
  #
  #  <data>
  #    <data type="array">
  #      <datum>
  #        ...
  #      </datum>
  #    </data>
  #    <meta>
  #      ...
  #    </meta>
  #  </data>
  #
  #
  # Instead we want it to look like this:
  #
  #  <root>
  #    <data type="array">
  #      <datum>
  #        ...
  #      </datum>
  #    </data>
  #    <meta>
  #      ...
  #    </meta>
  #  </root>
  def pretty_xml(resource_proxy)
    json = resource_proxy.to_json
    JSON.parse(json).to_xml(root: :root)
  end
end

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions