my $sXML = XML::Smart->new('file.xml', 'SMART'); my $pXML = XML::LibXML->load_xml('file.xml'); ### Basic Transversing ### # Smart = hash trees $sXML = $sXML->cut_root; my $book = $sXML->{book}[3]; print $book->{title}; # LibXML = no hash trees $pXML = $pXML->documentElement(); my $book = $pXML->childNodes()->[3]; print $book->findvalue('title'); # (though, XPaths makes it a little bit better...) print $pXML->findvalue('book[4]/title'); ############################## ### Array of values ### # Smart = simple and elegant $sXML = $sXML->cut_root; my @books = $sXML->{book}('@'); # LibXML = ugly, ugly, ugly $pXML = $pXML->documentElement(); my @books = map { $_->textContent } $pXML->find('book')->get_nodelist(); ############################## ### Creating a new XML doc ### # Smart = light on the code, and doesn't require searching for 500 methods my $sXML = XML::Smart->new(); $sXML->{root}->{'xmlns:xsi'} = "http://www.w3.org/2001/XMLSchema-instance"; $sXML->{root}->{'xsi:schemaLocation'} = "test.xsd"; $sXML->{root}->{'data'} = "Hello World!"; $sXML->{root}->{'data'}->set_node(); # LibXML = WTF?!? my $pXML = XML::LibXML::Document->new('1.0', 'UTF-8'); my $root = XML::LibXML::Element->new('root'); $root->setNamespace("http://www.w3.org/2001/XMLSchema-instance", 'xsi', 0); $root->setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", 'xsi:schemaLocation', "test.xsd"); $pXML->setDocumentElement($root); $root->addNewChild(undef, 'data')->setData("Hello World!"); ############################## ### Adding a new row of elements ### # Smart = blends in with Perl hashes my $node = ( 'title' => 'XML Schema', 'author' => 'Eric Van der Vlist', 'publisher' => "O'Reilly Media Inc.", 'phystype' => 'Paperback', 'year' => 2002, ); push(@{$sXML->{book}}, $node); # (though, this is a little ugly...) # LibXML = Bats**t crazy! my $node = XML::LibXML::Element->new('book'); $node->addNewChild(undef, 'title') ->setData('XML Schema'); $node->addNewChild(undef, 'author') ->setData('Eric Van der Vlist'); $node->addNewChild(undef, 'publisher')->setData("O'Reilly Media Inc."); $node->addNewChild(undef, 'phystype') ->setData('Paperback'); $node->addNewChild(undef, 'year') ->setData(2002); $sXML->appendChild($node); ### if exists OR define ### # Smart = a simple one-liner $row->{author} ||= "Freddy Krueger"; # LibXML = crappy $row->findvalue('author') || $row->addNewChild(undef, 'author')->setData("Freddy Krueger"); ############################## ### Searching ### # Smart = meh... my $book = $sXML->{book}('title', 'eq', 'XML Schema'); # LibXML = better, but... my $book = $pXML->find('book[title="XML Schema"]'); # ...this would be really cool my $book = $sXML->{book}('[title="XML Schema"]'); my $book = $sXML->('book[title="XML Schema"]'); ##############################