Preserving hierarchy when converting .csv file to xml or json

Posted by Simon Levinson on Stack Overflow See other posts from Stack Overflow or by Simon Levinson
Published on 2009-05-29T11:23:46Z Indexed on 2010/05/03 10:08 UTC
Read the original article Hit count: 395

Filed under:
|

Hello

I have a question concerning translating data from a CSV into XML or JSON where it is essential to preserve the heirarchy of the data.

For example, if I have CSV data like this:

type,brand,country,quantity
apple,golden_delicious,english,1
apple,golden_delicious,french,2
apple,cox,,4
apple,braeburn,,1
banana,,carribean,6
banana,,central_america,7
clememtine,,,3

What I want is to preserve hierarchy in the XML so that I get something like:

<fruit>
<type = "apple">
<brand = "golden_delicious">
<country = "english" quantity =  "1">
<country = "french" quantity =  "2">
</brand>
<brand = "cox">
<quantity =  "4">
</brand>
<brand = "braeburn">
<quantity =  "1">
</brand>
</type>
<type = "banana">
<country = "carribean" quantity =  "6">
<country = "central_america" quantity =  "7">
</type>
<type = "clementine">
<quantity =  "3">
</type>
<fruit />

Is it best to try to use JAXP or to convert the above into a table simply of parent, child and then writing the data to an array of strings for processing,? Like this:

parent,child 
fruit,apple
apple,golden_delicious
golden_delicious,english
golden_delicious,french
english,1
french,2
apple,cox
cox,4
apple,braeburn
braeburn,1

And so on.

Or is there a better way?

Thanks

Simon Levinson

© Stack Overflow or respective owner

Related posts about jaxp

Related posts about csv