Search code examples
scalaxstream

Convert json to XML with namespace and tokens in Scala


I have a json document like this:

{"orderNumber": "12345",
"date": "11/05/2011",
"fromInventoryLocation": "New York",
"toLocation": "Los Angeles",
"shippingMethod": "Ground",
"shipDate": "11/25/2014",
"shipTo": "123 Main St.",
"Items": [
   {"item": "shirt", "quantity": "2", "orderPriority": "Standard"}, 
]}

I initialize the XStream converter with:

val xstreamIB = xstream.XStreamConversions(new XStream(new DomDriver))

I use a case class Shipment to create the object and pass it to:

val xmlIB = xstreamIB.toXML(Shipment)

The output XML file returns:

<Shipment>
  <OrderNumber>12345</OrderNumber>
  <Date>11/05/2011</Date>
  <Address>
    <Street>123 Main St.</Street>
  </Address>
  <Etc>
    <Ex>...</Ex>
  </Etc>
</Shipment

The receiving API requires 2 things. A namespace in the opening Shipment tag; <Shipment xmlns="namespace">, and a token in the address tag; <Address type = "shipping">. I tried using .alias, but it modifies both the open and closing tag; throwing an error.

Is there a way to add the namespace and the token into the opening tags?


Solution

  • I was able to get the xml namespace using StaxDriver instead of DomDriver. The code below worked:

    val qmap = new QNameMap
      qmap.setDefaultNamespace("urn:namespace")
      val xmlOut = xstream.XStreamConversions(new XStream(new StaxDriver(qmap)))
    val xml = xmlOut.toXML(Shipment)