2011-10-27 34 views
-1

我有一个XML文件,我想以规范化的方式解析数据库。表二是我创建一对多关系表的想法。名称,标题永远不会改变每个文件组,但下载路径将不同。将XML文件解析为规范化数据库模式

表1

id | name  | title       | download_path 
---------------------------------------------------------------------- 
1 | FileGroup 1 | This is the first file group | /this/1/1.zip 
2 | FileGroup 1 | This is the first file group | /this/1/2.zip 
3 | FileGroup 2 | This is the second file group | /this/2/1.zip 
4 | FileGroup 2 | This is the second file group | /this/2/2.zip 
5 | FileGroup 3 | This is the third file group | /this/3/1.zip 

XML文件

<Item> 
    <Name>File Group 1</Name> 
    <Title>This is the first file group</Title> 
    <DownloadPath>/this/1/1.zip</DownloadPath> 
</Item> 
<Item> 
    <Name>File Group 1</Name> 
    <Title>This is the first file group</Title> 
    <DownloadPath>/this/1/2.zip</DownloadPath> 
</Item> 
<Item> 
    <Name>File Group 2</Name> 
    <Title>This is the second file group</Title> 
    <DownloadPath>/this/2/1.zip</DownloadPath> 
</Item> 
<Item> 
    <Name>File Group 2</Name> 
    <Title>This is the second file group</Title> 
    <DownloadPath>/this/2/2.zip</DownloadPath> 
</Item> 
<Item> 
    <Name>File Group 3</Name> 
    <Title>This is the third file group</Title> 
    <DownloadPath>/this/3/1.zip</DownloadPath> 
</Item> 

表2

group_id | file_id 
----------------------------- 
1  | 1 
1  | 2 
2  | 3 
2  | 4 
3  | 5 

什么是通过XML解析时,要做到这一点的最好办法。如果我将XML数据放入一个数组中并对每个项目进行foreach,则需要能够将它们即时分组,并在表2中创建关系。我确实有创建表1的想法,然后再构建关系表,但即使如此,然后我不知道如何最好的分组他们。我在XML中没有任何内容可以说他们被分组为其他名称和标题。每个组可以有任意数量的文件下载路径。

我对XML文件创建没有任何发言权。我必须处理的一切。

回答

0

您的表格结构没有标准化。您可以更新一个文件组/标题行而不更新其他文件,这将是错误的。相反,FileGroup/Title应该在一个表中,而FileGroup/download_path应该在另一个表中。

至于基于XML组织DB,设想你正在按节点解析XML:

$groups = array(); 
foreach ($Items as $Item) { 
    if (!isset($groups[$Item->Name])) { 
     $groups[$Item->Name] = array(
     'title' => $Item->Title 
     , 'files' => array(); 
    ); 
    } 
    $groups[$Item->Name]['files'][] = $Item->DownloadPath; 
} 

在您的示例XML也无效,运气这么好处理,如果这是它确实是..

+0

谢谢你是对的。我的XML很好,我只是很快编辑了上面的例子来简化它。我做了改变。我会再看看架构。 – madphp

+0

另外,上面的表格是数据库标准化中的第二种标准形式。我确实承认它可以更好。 – madphp

+0

@madphp表格不在2NF中。标题在功能上仅取决于名称。但是,名称不是候选键。这违反了2NF。 –