in reply to XML: Simple - nested XML data

I would use XML::XPath to access the nodes.

use strict; use XML::XPath; my $xml = '<SuperItem> <UserID>1234</UserID> <MajorItems> <MinorItem> <Item>Box</Item> </MinorItem> </MajorItems> <MajorItems> <MinorItem> <Item>Suitcase</Item> </MinorItem> </MajorItems> </SuperItem> '; my $xp = XML::XPath->new( xml => $xml ); my $path = '/SuperItem/MajorItems[2]/MinorItem'; print $xp->findnodes_as_string($path);
Returns:
<MinorItem> <Item>Suitcase</Item> </MinorItem>

Actually there are several XPath expressions which would give the same result, such as //MajorItems[2]/MinorItem or /SuperItem[UserID='1234']/MajorItems[2]/MinorItem. It will all depend on the actual content and structure of your XML.

Update: Changed XML::Xpath to XML::XPath. thx PipTigger!

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: XML: Simple - nested XML data
by PipTigger (Hermit) on Dec 28, 2007 at 05:18 UTC

    I think that should've been XML::XPath ... which I inherited from for my XML::Tidy module. You might try:

    #!/usr/bin/perl use strict; use warnings; use XML::XPath; my $xpob = XML::XPath->new('xml' => '<SuperItem> <UserID>1234</UserID> <MajorItems> <MinorItem> <Item>Box</Item> </MinorItem> </MajorItems> <MajorItems> <MinorItem> <Item>Suitcase</Item> </MinorItem> </MajorItems> </SuperItem>'); my @itmz = $xpob->findnodes('//Item'); # retn nodez in doc ordr print $itmz[1]->getChildNode(1)->getValue(); # XPath indices are 1-bas +ed # ... so the abov line takes the 2nd <Item /> elem (Bcuz Perl is 0-bas +ed) # && traverses down to its 1st child-node (this time no more nested el +emz # but just a TextNode as the only child) to print that value: "Suitcas +e"

    XPath is good shit. Just today, I used it in a COLLADA file with: '//node[@type="JOINT"]' to give me all the elements that describe animation bones for a Wii game I'm working on. Tim sure is Toady. ;) Have fun!

    -Pip@CPAN.Org
    PipForPresident.Org