[prev in list] [next in list] [prev in thread] [next in thread] 

List:       perl-xml
Subject:    Re: XML::LibXML::Reader
From:       Petr Pajas <pajas () ufal ! ms ! mff ! cuni ! cz>
Date:       2007-08-11 15:11:18
Message-ID: 200708111711.18441.pajas () ufal ! mff ! cuni ! cz
[Download RAW message or body]

On Saturday 11 August 2007, Browder, Tom wrote:
> I love the reader but am having problems getting attribute info.  I also
> have other questions:
>
> 1.  When I use readInnerXML and then use it as a string input to a new
> reader I get complaints about extra stuff at the end.

Hi Tom-
indeed, the new reader complains because what you feed to it is not a 
well-formed XML.

> So I have been using 
> readOuterXML and ignoring the parent element while parsing.  Is there any
> better way to isolate looking at an element's children?

yes, for example e.g. using the same reader and checking the value of depth(). 
readInnerXML and readOuterXML are not meant to be used for this purpose.

> 2. Can you show me exactly how to get the attribute/value pairs from this
> xml fragment:

Yes, see the following code:

#_____________

my $xml  = <<'EOF';
<parent a='A' b='B'>
  <child a='A' b='B'>
    <gchild a='A' b='B'>a</gchild>
  </child>
</parent>
EOF

use XML::LibXML;
use XML::LibXML::Reader;
my $r = XML::LibXML::Reader->new(string => $xml);
while ($r->read) {
  if ($r->nodeType == XML_READER_TYPE_ELEMENT) {
    print "-----------------\n";
    print "Element ". $r->name,"\n";

    # several ways of reading attributes:
    # read all attributes:
    if ($r->moveToFirstAttribute) {
      do {{
	print "Attribute ",$r->name(), " => ",$r->value,"\n";
      }} while ($r->moveToNextAttribute);
      $r->moveToElement;
    }
    # back at the element
    # ...

    # read a specific attribute:
    print "----\n";
    print "Attribute b: ",$r->getAttribute('b'),"\n";
  }
}

__END__
_______________________________________________
Perl-XML mailing list
Perl-XML@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic