Xpath问题,如果知道元素的标题,则获取元素的id(attribute) [英] Xpath problem, getting the id(attribute) of a element, if you know the title of the element

查看:123
本文介绍了Xpath问题,如果知道元素的标题,则获取元素的id(attribute)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的XML文件,当您知道
的标题是什么时,我想知道如何获取文章的ID。

This is my XML file, and i want to know how to get the ID of the article when you know what the title is. Is this possible using Xpath?

XML文件?

<Articles>
    <Article ID="1">
        <title>test</title>
        <content>test</content>
    </Article>
</Articles>

Php代码:

$dom = new DOMDocument;
$dom->load("Articles.xml");
$xp = new DOMXPath($dom);
$id = $xp->evaluate('string(/Articles/Article[title="test"]/@ID)');
var_dump($id);

亲切的问候,

用户。

推荐答案

只要使用SimpleXml,就不能直接返回ID。正确的XPath应该是

As long as you are using SimpleXml, you cannot return the ID directly. The correct XPath would be

/Articles/Article[title="crack"]/@ID

如其他地方所示。但是SimpleXml没有属性节点的概念。它只知道SimpleXmlElements。因此,您也可以获取文章节点

as shown elsewhere already. But SimpleXml has no concept of Attribute nodes. It only knows SimpleXmlElements. So you can just as well fetch the Article node instead

/Articles/Article[title="crack"]

因为最终您必须执行以下操作才能获得ID值:

because in the end you'll have to do the following to get the ID value anyway:

echo $articles[0]['id'];

请注意,从SimpleXml元素访问属性时不需要@。

Note that you do not need the @ when accessing the attribute from the SimpleXml Element.

如果您想直接获取ID属性,则必须使用DOM(代码键盘

If you wanted to fetch the ID attribute directly, you'd have to use DOM (codepad)

$dom = new DOMDocument;
$dom->loadXml($xml);
$xp = new DOMXPath($dom);
$id = $xp->evaluate('string(/Articles/Article[title="crack"]/@ID)');
var_dump($id);

只要没有其他带有title元素的节点等于上面的值,上面的内容将返回1

The above would return 1 as long as there is no other node with a title element with a value equal to "crack".

如果您的节点具有格式设置,则就像您的屏幕截图中显示的一样,您必须先对元素进行消毒,然后再测试其值。否则,将考虑用于格式化文档的空白。的XPath将是

In case you have nodes with formatting, like shown in your screenshot, you have to sanitize the element before testing for the value. Otherwise the whitespace used to format the document is taken into account. The XPath for that would be

string(/Articles/Article[normalize-space(title) = "crack"]/@ID)

如果您要搜索标题为包含的文章 crack部分,使用

If you want to search for articles with a title that contains "crack" in part, use

string(/Articles/Article[contains(title, "crack")]/@ID)

请注意,只要只有一个结果,这仍将立即返回ID。如果存在多个匹配节点,则将返回第一个ID值。使用

Note that this will still only return the ID immediately as long as there is just one result. If there is multiple matching nodes, the first ID value will be returned. Use

/Articles/Article[contains(title, "crack")]/@ID

返回所有匹配节点的DOMNodeList,然后对其进行迭代以获取其各自的ID值。

to return a DOMNodeList of all matching nodes and then iterate over them to get their individual ID values.

另请参见 PHP中SimpleXml的基本用法示例手动

这篇关于Xpath问题,如果知道元素的标题,则获取元素的id(attribute)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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