每个父节点具有不同数量的子节点的 XML [英] XML with varying amount of child nodes for each parent node
本文介绍了每个父节点具有不同数量的子节点的 XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我从文件test.xml"中读取了以下格式的 XML
So I have XML in the following format which I am reading from file '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>
我希望能够将上述内容输出为以下格式:
I want to be able to output the above into the following format:
Agent | Code | Name
ABC123 | XYZ | Hotel 1
ABC123 | 237 | Hotel 2
......
由于有多个 Agent 并且每个 Agent 中有不同数量的属性,我将如何执行此操作?
How would I do this as there are multiple Agents and a varying amount of Properties within each Agent?
我有使用 XMLReader 的经验,但很高兴尝试像 SimpleXML 这样的替代方案.
I have experience of using XMLReader but happy to try an alternative such as SimpleXML.
我想我需要在这个(Foreach Agent ....)上使用 Foreach 循环,但不太确定从哪里开始.
I think I would need to use a Foreach loop on this (Foreach Agent....) but not quite sure where to start.
谢谢!
推荐答案
看这个:
$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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文