http://www.perlmonks.org?node_id=8018

orthanc has asked for the wisdom of the Perl Monks concerning the following question:

Hi Again

As you guys were so much help with my last XML problem I have another I need help with.

Take this xml below, using XML::Parser I can gain access to the data between
the inside tags.

I need to be able to access the data stored in name,
as it is an attribute of the inside tag I can't figure out how to access it

Is there an option for XML::Parser to make it expand this kind of tag?

Example XML:
	<outside>
		<inside name="Wibble">some data</inside>
	</outside>

Thanks in advance, i'm sure someone will know the answer :)

Replies are listed 'Best First'.
Re: More with XML Parser
by btrott (Parson) on Apr 19, 2000 at 19:06 UTC
    What handlers are you using w/ XML::Parser? Or are you using one of the Styles? Ie. Tree style?

    If you're using a handler, you can get the data in "name" in your StartTag handler. The attributes are arguments to the handler, like this:

    my $data = <<STOP; <outside> <inside name="Wibble">some data</inside> </outside> STOP my $parser = new XML::Parser(Handlers => { Start => \&start_tag }); $parser->parse($data); sub start_tag { my $expat = shift; my $element = shift; my %attrs = @_; print $attrs{name}; }
    If you're using the Tree style, I'm not sure exactly where you can find the value of name... try using Data::Dumper to print out the tree and see where it shows up.
    use Data::Dumper; my $tree = $parser->parse($data); print Dumper $tree;
      With the Tree style, each element node is an array. The first member is the name of that element, the second is a reference to an array (the content of that element). The first item of that array is a hash reference which contains any attributes (or nothing, if there are none). The data structure looks something like this:
      [ "outside", [ "inside", [ { "name" => "Wibble"}, 0, "some data"] ] ]
      Yuck.
      Yeah, the Tree style is kind of icky, I think. :)

      To the OP: if your XML file is pretty simple, you should try using XML::Simple. It loads your data into a nice hash-of-hashes tree.

      use XML::Simple; my $xml = XMLin("foo.xml"); use Data::Dumper; print Dumper $xml;
      For your particular example, I got these results:
      $VAR1 = { 'inside' => { 'name' => 'Wibble', 'content' => 'some data' } };
      So you could get the contents of name like this:
      my $name = $xml->{'inside'}{'name'};