2010-03-01 128 views
3

我有一个包含国家和城市的数据库。我想将这些信息导出到一个XML文档,但不知道如何构造它。帮助构建xml文档

我应该做这样的:

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

或像这样:

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

或像这样:

<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> 

哪些利弊与他们每个人的?还有另一种结构化方式吗?

哪些是最适合将来的变化(添加数据)。

我第一次在xml中构建,所以会有很好的反馈/提示!

回答

3

您应该按照您在代码中构建类的相同方式构造XML文档。所以城市人口是城市本身的财产 - 它应该是城市节点的孩子。我会去第二个结构。

再加上它更有助于您的物体助记符。例如,你不清楚什么是“实体”在你的第二个解决方案中。

加上它减少了数据重复,因为你必须在每个实体中声明country = canada。不过,我会改变你的第一个解决方案。将国家/地区元素置于集合中:

<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> 

它将帮助您稍后扩展您的数据。

编辑:一般来说,当你有重复的对象时,最好把它们包装在'collection'元素中。这是一个很好的做法,因为您可以将属性添加到集合本身以及其他一些好处 - 您将不会重复父母的元素并选择哪一个属于同一类型。

+0

你是说第一个? – ajsie 2010-03-01 16:15:08

+0

绝对是第一个更好! – anthares 2010-03-01 16:18:27

+0

好的感谢您的更改。但我会在每个文件中有一个国家,这样在这种情况下就不需要了。 – ajsie 2010-03-01 16:21:23