Php next()元素SimpleXML
我有一个XML文件:Php next()元素SimpleXML,php,xml,simplexml,Php,Xml,Simplexml,我有一个XML文件: <?xml version="1.0" encoding="UTF-8"?> <dc> <category> <name>Personal Information</name> <type> <name>Age or Range</name> <item dc-numeric="1"&g
<?xml version="1.0" encoding="UTF-8"?>
<dc>
<category>
<name>Personal Information</name>
<type>
<name>Age or Range</name>
<item dc-numeric="1">Record 1</item>
<item dc-numeric="2">Record 2</item>
<item dc-numeric="3">Record 3</item>
</type>
<type>
<name>Preferences</name>
<item dc-numeric="1">Record 1</item>
<item dc-numeric="2">Record 2</item>
<item dc-numeric="3">Record 3</item>
</type>
</category>
<category>
<name>Product Information</name>
<type>
<name>Intellectual Property</name>
<item dc-numeric="1">Record 1</item>
<item dc-numeric="2">Record 2</item>
<item dc-numeric="3">Record 3</item>
</type>
</category>
<category>
<name>Business Information</name>
<type>
<name>Business Records</name>
<item dc-numeric="1">Record 1</item>
<item dc-numeric="2">Record 2</item>
<item dc-numeric="3">Record 3</item>
</type>
</category>
</dc>
我试图获得以下输出,以在XML中显示上一个/下一个类别->名称:
个人信息
- 产品信息
产品信息
- 个人信息|业务信息
Xpath允许您使用表达式获取DOM的一部分(SimpleXML基于DOM)
它有上下文和轴的概念。默认轴是子节点
——节点的子节点。在这种情况下,您需要前面的兄弟姐妹
和后面的兄弟姐妹
<代码>[1]
是列表中第一个节点的条件,由其前面的位置路径描述
下面是一个如何使用它们的小示例:
$dc = new SimpleXMLElement($xml);
foreach ($dc->category as $category) {
$previous = $category->xpath('preceding-sibling::category[1]')[0];
$next = $category->xpath('following-sibling::category[1]')[0];
var_dump(
[
'current' => (string)$category->name,
'previous' => $previous instanceof SimpleXMLElement
? (string)$previous->name : null,
'next' => $next instanceof SimpleXMLElement
? (string)$next->name : null,
]
);
}
输出:
array(3) {
["current"]=>
string(20) "Personal Information"
["previous"]=>
NULL
["next"]=>
string(19) "Product Information"
}
array(3) {
["current"]=>
string(19) "Product Information"
["previous"]=>
string(20) "Personal Information"
["next"]=>
string(20) "Business Information"
}
array(3) {
["current"]=>
string(20) "Business Information"
["previous"]=>
string(19) "Product Information"
["next"]=>
NULL
}
我将您的XML直接复制到您的问题中。可以在场外提供补充信息,但您的问题基本上应该是独立的。谢谢。下次我会记得的
array(3) {
["current"]=>
string(20) "Personal Information"
["previous"]=>
NULL
["next"]=>
string(19) "Product Information"
}
array(3) {
["current"]=>
string(19) "Product Information"
["previous"]=>
string(20) "Personal Information"
["next"]=>
string(20) "Business Information"
}
array(3) {
["current"]=>
string(20) "Business Information"
["previous"]=>
string(19) "Product Information"
["next"]=>
NULL
}