XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).
Moderator: General Moderators
McManCSU
Forum Newbie
Posts: 22 Joined: Mon Apr 23, 2007 6:30 pm
Post
by McManCSU » Thu May 24, 2007 5:23 pm
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!
volka
DevNet Evangelist
Posts: 8391 Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger
Post
by volka » Thu May 24, 2007 9:57 pm
Do you want it to print "xyz", "zyx", "abc"
or "server", "xyz", "zyx" , "abc"?
What if there is <server><xyz><foo></foo></xyz>.... ?
McManCSU
Forum Newbie
Posts: 22 Joined: Mon Apr 23, 2007 6:30 pm
Post
by McManCSU » Fri May 25, 2007 9:59 am
There will be children with children, with children, etc. How about both answers?
Thanks
volka
DevNet Evangelist
Posts: 8391 Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger
Post
by volka » Fri May 25, 2007 11:47 am
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";
}
McManCSU
Forum Newbie
Posts: 22 Joined: Mon Apr 23, 2007 6:30 pm
Post
by McManCSU » Fri May 25, 2007 12:56 pm
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
volka
DevNet Evangelist
Posts: 8391 Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger
Post
by volka » Fri May 25, 2007 11:05 pm
You should consider
xsl for this.
Ambush Commander
DevNet Master
Posts: 3698 Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US
Post
by Ambush Commander » Sat May 26, 2007 8:17 am
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.
volka
DevNet Evangelist
Posts: 8391 Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger
Post
by volka » Wed May 30, 2007 1:24 am
But that doesnÄt help you with
McManCSU wrote: Also, is it possible to format it dependent on which sub element it is?