Page 1 of 1

XML - How to print all children nodes?

Posted: Thu May 24, 2007 5:23 pm
by McManCSU
I am trying to print all children nodes of a parent node, but I cannot figure out how... This is what I am doing:

Code: Select all

<server>
  <xyz>
   ...
   </xyz>
  <zyx>
   ...
   </zyx>
  <abc>
   ...
   </abc>
</server>

Code: Select all

$_doc = new DOMDocument();
	$_doc->load(SERVER_PATH);

        $_serverTag = $_doc->getElementsByTagName("server");	

	foreach ($_serverTag as $tag)
	{
	    echo $tag->nodeName;
	}
All it does is output "server", and not "xyz", "zyx" or "abc", like I want it to... Thanks!

Posted: Thu May 24, 2007 9:57 pm
by volka
Do you want it to print "xyz", "zyx", "abc"
or "server", "xyz", "zyx" , "abc"?

What if there is <server><xyz><foo></foo></xyz>.... ?

Posted: Fri May 25, 2007 9:59 am
by McManCSU
There will be children with children, with children, etc. How about both answers?

Thanks

Posted: Fri May 25, 2007 11:47 am
by volka
Here you are

Code: Select all

<?php
$xml = <<< eox
<server>
	<xyz>
		<abc>
			<def></def>
		</abc>
	</xyz>
	<xyz>
		<abc>
			<def>
				<ghi></ghi>
			</def>
		</abc>
	</xyz>
	<zyx>
	...
	</zyx>
</server>
eox;

$dom = DOMDocument::loadxml($xml);
$xpath = new DOMXPath($dom);

echo "only direct children of server : <br />\n";
$nodeset = $xpath->query('//server/*');
foreach($nodeset as $n) {
	echo 'name: ', $n->tagName, "<br />\n";
}

echo "<hr />\n";

echo "all descendants of server : <br />\n";
$nodeset = $xpath->query('//server/descendant::*');
foreach($nodeset as $n) {
	echo 'name: ', $n->tagName, "<br />\n";
}

Posted: Fri May 25, 2007 12:56 pm
by McManCSU
Is it possible to print any attributes? ie: <xyz id="1">? Also, is it possible to format it dependent on which sub element it is?

Thanks

Posted: Fri May 25, 2007 11:05 pm
by volka
You should consider xsl for this.

Posted: Sat May 26, 2007 8:17 am
by Ambush Commander
I agree that, at this point, you should use XSLT, but if you need a quick fix, the variable $n in the loop represents a node, and can be queried for attributes.

Posted: Tue May 29, 2007 3:42 pm
by McManCSU
Thanks for the help. I found my last answer on http://www.w3schools.com/xpath/xpath_syntax.asp

All I have to do is something like:

Code: Select all

query(//xyz[@id='1'])

Posted: Wed May 30, 2007 1:24 am
by volka
But that doesnÄt help you with
McManCSU wrote:Also, is it possible to format it dependent on which sub element it is?