Use Xpath to find XML nodes with a specific child element
I'm new to the world of XPath. I'm wanting to take an XML approach to powering my simple portfolio website instead of a database, which in this case would be superfluous as the only database element would be the projects the开发者_如何学JAVAmselves.
I've authored an XML file with the following structure:
<?xml version="1.0" encoding="UTF-8" ?>
<projects>
<project>
<title>A-Merchandise</title>
<slug>a-merchandise</slug>
<projectType>E-commerce</projectType>
<launchDate>2007-08-01</launchDate>
</project>
...
Now, I can parse this XML file fine with PHP for a listing overview, but how do I go about filtering projects with XPath? For example, how do I obtain all project
nodes that has a child projectType
node with the value e-commerce
?
Normally, I would run a SQL query like:
SELECT * FROM `projects` WHERE `category` = 'e-commerce';
What would the XPath equivalent be? Is my XML file in the right structure to accomodate this filtering?
Any pointers would be great. Thanks in advance.
I believe you want this:
/projects/project[projectType="e-commerce"]
The []
filter selects all project
elements under projects
who have a projectType
child with value "e-commerce"
I've also found this site to be very helpful for messing around with XPath and XSLT queries.
Further reading: http://www.w3schools.com/xpath/xpath_syntax.asp
considering your xml file name is foo.xml and is in same dir of bar.php which has content
$projects = simpleXMLElement('foo.xml',null,true);
$ecomProjects = $projects->xpath('project[projectType="E-commerce"]');
foreach($ecomProjects as $ecomProject)
{
echo $ecomProject; // or do whatever with it
}
You can use XPath filers, like that:
//project[projectType='E-commerce']
In the documentation of XPath ( http://www.w3.org/TR/xpath/#predicates ), there is this example:
chapter[title="Introduction"]
selects thechapter
children of the context node that have one or moretitle
children with string-value equal toIntroduction
Bone up on xpath, it is very useful. Althought I don't like w3cshools in general, their xpath docs are pretty good.
$doc = new DOMDocument();
$xpath = new DOMXpath($doc);
foreach ($xpath->query("/projects/project") as $node)
{
if ($node->textContent == "e-commerce")
{
// this node is the one you want.
}
}
or using pure xpath
foreach ($xpath->query("/projects/project[projectType = 'e-commerce']") as $node)
{
// grab the $node
}
Some pointers
To select a node anywhere in the doc prefix with double slashes i.e. //nodeYouWant
. To select an attribute use @
i.e. /nodeName[@attribute='attributeValue']
syntax.
W3schools is a good place to start.
I would probably change projectType into an attribute of project and then select like this:
//project[@projectType ='e-commerce']
精彩评论