2010-03-01 104 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