Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find parents & children by node content of XLM

Status
Not open for further replies.

beltmanjr

Technical User
Oct 29, 2007
333
NL
Hi there,
I am trying to quickly find the parent and child nodes of a node with a particular contents value.

Like from the sample xml below I'd like to find the parent+child nodes for the contents 'Computer'. I would expect to find books/store[0]/book[0]/genre

Is there any way of doing this? I don't know what to look for on google.

Sample XML:
<books>
<store id="01">
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
</book>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
</book>
</store>
 
Hi there,
I have no idea what the key will be, but know its contents.
The key can differ all the time.
 
maybe this might help. it will filter the books which match your criteria

Code:
<?php
$xml = <<<XML
<books>
<store id="01">
<book id="bk101">
  <author>Gambardella, Matthew</author>
  <title>XML Developer's Guide</title>
  <genre>Computer</genre>
  <price>44.95</price>
</book>
<book id="bk102">
  <author>Ralls, Kim</author>
  <title>Midnight Rain</title>
  <genre>Fantasy</genre>
  <price>5.95</price>
</book>
</store> 
</books>
XML;
$s = new simplexmlelement($xml);
echo '<pre>';
print_r(searchfor('computer', $s));
function searchfor($needle, $s){
	$results = array();
	foreach($s->children() as $store){
		//get store ID
		foreach($store->Attributes() as $a=>$v){
			if ($a == 'id'){
				$storeID = $v;
			}
		}
		foreach ($store->children() as $book){
			foreach($book->Attributes() as $a=>$v){
			if ($a == 'id'){
				$bookID = $v;
			}
			$array = array('author','title','genre','price');
			foreach($array as $item){
				if(strtolower($book->$item) == strtolower($needle) ){
					$book->id = $bookID;
					$book->storeID = $storeID;
					$results[] = $book;
					
				}
			}
		}
		}
	}
	return $results;
}
 
Hi Jpadie,
you have given me an idea indeed.

The current issue is that I dont know what the xml will really look like and that a number of different xml files will come my way. All I do know is the wording we'll look for.

But you have given me an idea on how to resolve this now. Cheers for that.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top