Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Xpath to find XML nodes with a specific child element

Tags:

php

xml

xpath

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 themselves.

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.

like image 812
Martin Bean Avatar asked Feb 28 '11 18:02

Martin Bean


2 Answers

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

like image 99
Jonathan B Avatar answered Oct 16 '22 23:10

Jonathan B


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
}
like image 6
Mr Coder Avatar answered Oct 16 '22 23:10

Mr Coder