XPath 评估查询并检索值 [英] XPath evaluate a query and retrieve the value

查看:18
本文介绍了XPath 评估查询并检索值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

$XMLTranslationObject = new DOMDocument();
$XMLTranslationObject->load("../xdata/xml/translation/en-US/profile.xml");

$Xpath = new DOMXpath($XMLTranslationObject);
$Result = $Xpath->evaluate("Field[@Name = 'AttachedFiles']")->nodeValue;

echo $Result;

和 xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<Translation language="en-US">

    <!-- Basic Begin -->
        <Field Name="SiteName">Brainfavor</Field>
        <Field Name="Error">Error</Field>
    <!-- Basic End -->

    <!-- Header Begin -->
        <Field Name="Name">Name</Field>
        <Field Name="WorkingAt">Working at</Field>
        <Field Name="Phone">Phone</Field>

witch 给我以下错误

witch gives me the following error

注意:未定义的属性:DOMNodeList::$nodeValue in C:\xampp\htdocs\brainbook\profile\loadmore.php 第 30 行

Notice: Undefined property: DOMNodeList::$nodeValue in C:\xampp\htdocs\brainbook\profile\loadmore.php on line 30

我想要的只是检索字段名称为 AttachedFiles 的行的值,只需运行一个简单的 Xpath 查询并检索结果.使用 XSLT 很容易

All i want is to retrieve the value of a row where field name is AttachedFiles , just run a simple Xpath query and retrieve the result. Using XSLT it is easy

<xsl:value-of select="$TranslationProfile/Field[@Name = 'AttachedFiles']"/>

但我之前没有使用过 PHP Xpath.

but i didn't used PHP Xpath before.

推荐答案

正确的表述是

$Xpath->evaluate("string(Field[@Name = 'AttachedFiles'])");

这是有效的,因为 string函数将节点集(在这种情况下实际上仅由一个节点组成)转换为集合中第一个节点的值.

This works because the string function converts the node set (which actually would consist of just one node in this case) to the value the first node in the set.

警告:这意味着如果有多个元素与查询匹配,则只有第一个(按文档顺序)将返回其值.

Warning: this means that if there are multiple elements that match the query only the first one (in document order) will have its value returned.

这篇关于XPath 评估查询并检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆