每个父节点具有不同数量的子节点的 XML


XML with varying amount of child nodes for each parent node

所以我有以下格式的XML,我正在从文件'test.xml中读取

<XML>
<Agent ID="ABC123">
    <Property>
        <Code>XYZ</Code>
        <Name>Hotel 1</Name>
    </Property>
    <Property>
        <Code>237</Code>
        <Name>Hotel 2</Name>
    </Property>
    <Property>
        <Code>213</Code>
        <Name>Hotel 3</Name>
    </Property>
</Agent>
<Agent ID="DEF456">
    <Property>
        <Code>333</Code>
        <Name>Hotel 4</Name>
    </Property>
    <Property>
        <Code>23423</Code>
        <Name>Hotel 5</Name>
    </Property>
</Agent>
<Agent ID="GHI789">
    <Property>
        <Code>45345</Code>
        <Name>Hotel 6</Name>
    </Property>
</Agent>
</XML>

我希望能够将上述内容输出为以下格式:

Agent | Code | Name
ABC123 | XYZ | Hotel 1
ABC123 | 237 | Hotel 2
......

由于有多个代理和每个代理中的属性数量不同,我将如何执行此操作?

我有使用XMLReader的经验,但很乐意尝试SimpleXML等替代方案。

我想我需要在这个(Foreach 代理...)上使用 Foreach 循环,但不太确定从哪里开始。

谢谢!

看看这个:

$sxe = new SimpleXMLElement($xmlstr);
echo 'Agent | Code | Name'.PHP_EOL;
foreach ( $sxe->Agent as $agent )
{
    $attr = $agent->attributes();
    foreach ( $agent->Property as $property )
    {
        echo $attr['ID'].' | '.$property->Code.' | '.$property->Name.PHP_EOL;       
    }
}