【问题标题】:XML XPath problemsXML XPath 问题
【发布时间】:2011-08-07 17:00:19
【问题描述】:

我是 Xpath 的新手,实际上今天才第一次看到它,我遇到了一些问题,即 XPath 无法加载 XML 中定义的图像。

到目前为止我有:

<page name = "home"><br />
<image>
        <imagehome1>
            <imge>resp.jpg</imge><br />
            <class>right</class>
        </imagehome1>
        <imagehome2>
            <imge></imge><br />
            <class>right</class>
        </imagehome2>
        <imagehomebot>
            <imge>cfr.png</imge><br />
            <class>bottom</class>
        </imagehomebot>
    </image>
</page>

如您所见,我定义了 2 个图像,1 个在 imagehome1 中,1 个在 imagehomebot 中,但是我的 XPath 代码只显示来自 imagehomebot 的图像.....我不知道为什么。

我的 PHP XPath 代码是:

<? 
                $nodes = $dom->xpath('/content/page/image/imagehome1');
                if (count($nodes) > 0) {
                    if(!(string)$nodes[0]->imge){
                        $class = "";}
                    else{
                    $class3 = (string)$nodes[0]->class;
                    $img3 = (string)$nodes[0]->imge;}
                }
            ?>
    <div class="<? echo $class ?>">
        <img src="imgs/<? echo $img1 ?>" />
    </div>

    <? 
                $nodes = $dom->xpath('/content/page/image/imagehome2');
                if (count($nodes) > 0) {
                    if(!(string)$nodes[0]->imge){
                        $class = "";}
                    else{
                    $class3 = (string)$nodes[0]->class;
                    $img3 = (string)$nodes[0]->imge;}
                }
            ?>

    <div class="<? echo $class ?>">
        <img src="imgs/<? echo $img2 ?>" />
    </div>

    </div>


    <div id="box2">

    <? 
                $nodes = $dom->xpath('/content/page/image/imagehomebot');
                if (count($nodes) > 0) {
                    if(!(string)$nodes[0]->imge){
                        $class = "";}
                    else{
                    $class3 = (string)$nodes[0]->class;
                    $img3 = (string)$nodes[0]->imge;}
                }
            ?>

<div class="<? echo $class3 ?>">
        <img src="imgs/<? echo $img3 ?>" />
    </div>

非常感谢所有帮助。 谢谢

编辑:刚刚又快速查看了我的代码,我想我知道为什么了,该死的复制粘贴哈哈...

【问题讨论】:

  • 所有这些图像都存在吗? HTML 输出是什么样的?
  • 实际显示 imagehomebot 图像的代码在哪里?
  • 这可能与'imgs'文件夹后缺少的'/'有关,但既然它现在神奇地出现了,你的问题可能会解决,对吧? :)
  • 不,以上都不是,如果您仔细查看编号方案,变量不匹配大声笑。如果你看看我的 OP EDIT。我一直在复制和粘贴很多东西,这就是发生这种情况的原因
  • 啊,是的,我明白了。设置 $img3 并输出 $img2。 :)

标签: php xml xpath


【解决方案1】:

看起来你想对所有包含 imge 节点的节点进行相同的处理。

试试

'/内容/页面/图像/*[图像]'

使用一个 xpath 获取 imagehome1、imagehome2 和 imagehomebot。如果您想将节点限制为具有实际字符串的节点,则可能类似于

/content/page/image/*[imge/text()]

“[]”中的表达式是“谓词”,它指定与它前面的“上下文”节点(“*”)相关的条件,表示获取图像的所有子节点。 (我这样做是因为它们的名称不同。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多