savonrb / nori

XML to Hash translator

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Use schema

digitalheir opened this issue · comments

Suppose we have the following XML:

 <root>
     <a>
         <b />
      </a>
      <a>
         <b />
         <b />
      </a>
 </root>

Nori will create the following hash:

{"root"=>{"a"=>[{"b"=>nil}, {"b"=>[nil, nil]}]}}

If we have the following document schema:

 <xsd:complexType name="a">
    <xsd:sequence>
        <xsd:element name="b" minOccurs="0" maxOccurs="unbounded" type="xsd:string"/>
    </xsd:sequence>
</xsd:complexType>

element ['root']['a'][0]['b'] should return a single-valued array, but there is no way to specify this to Nori.

This issue is a massive head ache especially when you are dealling with a response that has many associations that may be a single result or mutliple results. This means you either have to write a response formattter to correct this or use inflections some how. 😢

@andrew-whitmore, I ended up using this excellent XSLT for converting XML to JSON: https://github.com/bramstein/xsltjson

You could choose an XML conversion convention, depending on your needs and how convoluted your XML is. In my case, I'm dealing with really convoluted XML, so I ended up using the really verbose rayfish conversion convention but at least it always produces uniform results: arrays for everything.

You'll need a good XSLT 2.0 compliant library for that purpose though: I couldn't find a suitable one in Ruby, so I ended up using the saxon9 Java library in production.

So yeah, a bit complicated solution but it works pretty well for me.