问题描述
我有以下 XML 文件
I have the following XML file
<Item>
<name>...</name>
<id>...</id>
<ImageSets>
<ImageSet Category="variant">
<SwatchImage>
<URL>...</URL>
<Height Units="pixels"></Height>
<Width Units="pixels"></Width>
</SwatchImage>
<SmallImage>
<URL>...</URL>
<Height Units="pixels"></Height>
<Width Units="pixels"></Width>
</SmallImage>
</ImageSet>
<ImageSet Category="primary">
<SwatchImage>
<URL>...</URL>
<Height Units="pixels"></Height>
<Width Units="pixels"></Width>
</SwatchImage>
<SmallImage>
<URL>...</URL>
<Height Units="pixels"></Height>
<Width Units="pixels"></Width>
</SmallImage>
</ImageSet>
</ImageSets>
</Item>
<Item>....</Item>
然后我使用 PHP 遍历文件中的 Item 节点.
Then I use PHP to iterate through Item nodes within file.
foreach ($Xml as $item){
$name = $item->name;
$ID = $item->id;
};
等等.该代码可以完美地为每个项目提取名称和 ID.
And so on. The code works perfect extracting names and Id's for every item.
现在我的问题是提取 ImageSet Category='primary'->SmallImage->URL.ImageSet 节点不按任何特定顺序排列,因此有时主要"会在前,有时会是变体",这就是为什么 $item->ImageSets->ImageSet[1]
不是解决方案的原因
Now my problem is to extract ImageSet Category='primary'->SmallImage->URL. ImageSet nodes do not go in any particular order, so sometimes 'primary' will be first, sometimes 'variant', that's why $item->ImageSets->ImageSet[1]
is not a solution
所以在我的主要 foreach 循环中,我尝试使用 xpath 如下:
So within my main foreach loop I've tried using xpath as follows:
$src='';
foreach ($item->ImageSets->xpath('//ImageSet[@Category="primary"]') as $img){
$src = $img->MediumImage->URL;
};
绝对没有运气.
任何想法将不胜感激.
推荐答案
您在 XPath 表达式中有错误.如果表达式以 /
开头,则它是相对于文档本身的.您希望它相对于当前节点.这意味着您有两种可能的解决方案
You have an error in the XPath expression. If the expression starts with an /
it is relative to the document itself. You want it relative to the current node. This means you have two possible solutions
这将扩展为 child::ImageSet
.它获取作为上下文节点的直接子节点的 ImageSet
元素节点.
This expands to child::ImageSet
. It fetches the ImageSet
element nodes that are direct children of the context node.
扩展并标准化为 descendant::ImageSet
.它获取当前上下文中的任何 ImageSet
,即使它不是直接子元素..
代表当前节点,//
将轴更改为后代.
Expands and normalizes to descendant::ImageSet
. It fetches any ImageSet
inside the current context, even if it is not a direct child. The .
represents the current node and //
changes the axis to descendants.
这篇关于选定节点内的 SimpleXML xpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!