Xpath 问题,如果您知道元素的标题,则获取元素的 id(属性)
这是我的XML文件,我想知道如何获取文章的ID 标题是什么。使用 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);
亲切的问候,
用户。
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 file:
<Articles>
<Article ID="1">
<title>test</title>
<content>test</content>
</Article>
</Articles>
Php code:
$dom = new DOMDocument;
$dom->load("Articles.xml");
$xp = new DOMXPath($dom);
$id = $xp->evaluate('string(/Articles/Article[title="test"]/@ID)');
var_dump($id);
Kind regards,
User.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要您使用 SimpleXml,就无法直接返回 ID。正确的 XPath
已经如其他地方所示。但SimpleXml没有属性节点的概念。它只知道 SimpleXmlElements。因此,您也可以获取 Article 节点,
因为最终您必须执行以下操作才能获取 ID 值:
请注意,从 SimpleXml 元素访问属性时不需要 @。
如果您想直接获取 ID 属性,则必须使用 DOM (codepad)
上面将返回1,只要没有其他节点的 title 元素的值等于“crack”。
如果您的节点具有格式,如屏幕截图所示,则必须清理该元素在测试该值之前。否则,将考虑用于格式化文档的空白。 注意,
如果您想搜索标题包含部分“crack”的文章,请使用
只要只有一个结果,这仍然只会立即返回 ID 。如果有多个匹配节点,则返回第一个ID值。用于
返回所有匹配节点的 DOMNodeList,然后迭代它们以获取它们各自的 ID 值。
另请参阅 PHP 手册中的 SimpleXml 的基本使用示例
As long as you are using SimpleXml, you cannot return the ID directly. The correct XPath would be
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
because in the end you'll have to do the following to get the ID value anyway:
Note that you do not need the @ when accessing the attribute from the SimpleXml Element.
If you wanted to fetch the ID attribute directly, you'd have to use DOM (codepad)
The above would return 1 as long as there is no other node with a title element with a value equal to "crack".
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
If you want to search for articles with a title that contains "crack" in part, use
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
to return a DOMNodeList of all matching nodes and then iterate over them to get their individual ID values.
Also see the basic usage examples for SimpleXml in the PHP Manual
路径
应该可以做到。您不必遍历节点。
The path
should do it. You shouldn't have to iterate through the nodes.