Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

help with structuring xml document

Tags:

xml

i have a database that contains countries and cities. i want to export this information to a xml document, but wonder how to structure it.

should i do it like this:

<country>
 <name>Canada</name>
 <city>
  <name>Toronto</name>
  <population>1423200</population>
 </city>
 <city>
  <name>Ottawa</name>
  <population>1423200</population>
 </city>
</country>

or like this:

<country>
  <name>Canada</name>
  <cities>
     <city>
      <name>Toronto</name>
      <population>1423200</population>
    </city>
    <city>
      <name>Ottawa</name>
      <population>1423200</population>
    </city>
  </cities>
</country>

or like this:

<entity>
 <country>Canada</country>
 <city>Ottawa</city>
 <city_population>1423200</city_population>
</entity>
<entity>
 <country>Canada</country>
 <city>Toronto</city>
 <city_population>1423200</city_population>
</entity>

what are the pros and cons with each of them? is there another way of structuring?

which of them is best for future changes (adding data).

my first time to structure in xml, so would be great with feedbacks/hints!

like image 581
ajsie Avatar asked Apr 28 '26 14:04

ajsie


1 Answers

You should structure you XML Documents in the same manner you would structure you class in the code. So as cities population is property of the city itself - it should be child of the city node. I would go for the 2nd structure.

Plus it's more mnemonic about your objects. For example it's not clear what 'entities' stays for in your second solution.

Plus it has less data repetition, as you have to state the country=canada in every entity. I would make a change to you first solution, though. Put the Country element in a collection:

<countries>
<country>
 <name>Canada</name>
 <cities>
 <city>
  <name>Toronto</name>
  <population>1423200</population>
 </city>
 <city>
  <name>Ottawa</name>
  <population>1423200</population>
 </city>
 </cities>
</country>
</countries>

It will help you extend later your data.

EDIT: In general, when you have a repetition of objects it's better to wrap them in a 'collection' element. It's a good practice since you can add properties into the collection itself and some other benefits - you won't have iterate in to the parents' elements and choose which one belongs to the same type.

like image 173
anthares Avatar answered Apr 30 '26 21:04

anthares



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!