通过XML迭代

时间:2012-07-25 12:05:44

标签: php xml simplexml

XML:

<?xml version="1.0" encoding="utf-8"?>
    <NConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <NDomain>ex1</NDomain>
            <Parameters>
                <version>p</version>
                <siteFolder>site1</siteFolder>
                <cssGeneral></cssGeneral>
                <cssLogin>l.css</cssLogin>
            </Parameters>
            <Database>
                <hostname>898</hostname>
                <username>j</username>
                <password>k</password>
                <name>n</name>
            </Database>
<NDomain>ex2</NDomain>
                <Parameters>
                    <version>p</version>
                    <siteFolder>site1</siteFolder>
                    <cssGeneral></cssGeneral>
                    <cssLogin>l.css</cssLogin>
                </Parameters>
                <Database>
                    <hostname>898</hostname>
                    <username>j</username>
                    <password>k</password>
                    <name>n</name>
                </Database>
        </NConfig>

我想通过ex1

下的所有节点进行迭代

到目前为止,我可以通过这样做直接访问节点:

$xmldata  = simplexml_load_file("config.xml");

foreach($xmldata->Parameters as $item)
{
        echo "<p>Version: " . $item->version . "</p>";
        echo "<p>Site Folder: " . $item->siteFolder . "</p>";
}

但这并不会使其特定于根节点,而是会迭代列表中的所有参数。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

如果您的<Parameters><Database>具体针对相应的<NDomain>,我希望您应该使用这样的ur xml架构:

     <NDomain>
            <name>ex1</name>
            <Parameters>
                <version>p</version>
                <siteFolder>site1</siteFolder>
                <cssGeneral></cssGeneral>
                <cssLogin>l.css</cssLogin>
            </Parameters>
            <Database>
                <hostname>898</hostname>
                <username>j</username>
                <password>k</password>
                <name>n</name>
            </Database>
      </NDomain>
      <NDomain>
        <name>ex2</name>
                <Parameters>
                    <version>p</version>
                    <siteFolder>site1</siteFolder>
                    <cssGeneral></cssGeneral>
                    <cssLogin>l.css</cssLogin>
                </Parameters>
                <Database>
                    <hostname>898</hostname>
                    <username>j</username>
                    <password>k</password>
                    <name>n</name>
                </Database>
      </NDomain>

所以你可以像这样解析:

   foreach($xmldata->NDomain as $item)
   {
     $par = $item->Parameters;
    echo "<p>Version: " . $par->version . "</p>";
    echo "<p>Site Folder: " . $par->siteFolder . "</p>";
   }

答案 1 :(得分:0)

您可以遍历根节点子节点,如下所示:

$first = true;
foreach($xmldata->children() as $item)
{
    if( $first === true) { 
        $first = false;
        continue;
    }
}

该循环将捕获<NDomain><Parameters><Database>,因此您需要进行简单检查才能跳过第一次迭代以省略<NDomain>