-->

XML具有不同的子节点的数量为每一父节点(XML with varying amount of ch

2019-07-30 03:35发布

所以,我在下面的格式,我从文件“的test.xml”读取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循环,但不太知道从哪里开始。

谢谢!

Answer 1:

看这个:

$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;       
    }
}


文章来源: XML with varying amount of child nodes for each parent node