Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

simplexml - show path to element

7:13 am on Oct 14, 2010 (gmt 0)

Junior Member

10+ Year Member

joined:Jan 18, 2006
votes: 0

Hi, I have feed different XML files with different formats that I want to let users map to our database themselves. Example

<name>Product One</product>

What I need to do is be able to loop through the XML document and output the path for each element i.e.

name = "product>details->name"
cost = "product->details->cost"

Like I said there is a different and unknown format for each XML doc.

Any suggestions gratefully received. I have a process that can pull out the asset names i.e. width, height etc but not the path within the document.

Many thanks
2:46 pm on Oct 15, 2010 (gmt 0)

Senior Member

WebmasterWorld Senior Member 5+ Year Member

joined:Apr 30, 2007
votes: 0

Are you using PHP? Here is couple of functions I did

function recxml_array($object=null, &$result_array=array()) {
if(is_object($object) ) {
$name = $object->getName();
if( !isset($result_array[$name]) ) {
$result_array[$name] = array();
foreach($object->children() as $element) {
recxml_array($element, $result_array[$name]);

function recxml_display($input_array, &$string = '') {
if( empty($input_array) || !is_array($input_array) ) {
echo $string . '<br />';
$string = '';

foreach($input_array as $key => $value ) {
$org_string = $string;
$string .= (!empty($string)?'&nbsp;&raquo;&nbsp;':'') . $key;
recxml_display($value, $string);
$string = $org_string;
$xml = new SimpleXMLElement($string);
recxml_array($xml, $result_array);

The first function iterates through the xml object building up an md array that holds the xml elements as keys. The second function processes the php array to display the paths. It should work regardless of paths. Here is some XML for testing, just assign it to the $string var which is basically the input:

$string = <<<XML
<title>My Title</title>
<date>Jan 2009</date>
<item>An Item</item>