Xpath problem, getting the id(attribute) of a element, if you know the title of the element
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&g开发者_开发技巧t;
<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.
As long as you are using SimpleXml, you cannot return the ID directly. The correct XPath would be
/Articles/Article[title="crack"]/@ID
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"]
because in the end you'll have to do the following to get the ID value anyway:
echo $articles[0]['id'];
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)
$dom = new DOMDocument;
$dom->loadXml($xml);
$xp = new DOMXPath($dom);
$id = $xp->evaluate('string(/Articles/Article[title="crack"]/@ID)');
var_dump($id);
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
string(/Articles/Article[normalize-space(title) = "crack"]/@ID)
If you want to search for articles with a title that contains "crack" in part, use
string(/Articles/Article[contains(title, "crack")]/@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
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
/Articles/Article[title = "crack"]/@ID
should do it. You shouldn't have to iterate through the nodes.
精彩评论