<update nr="4"> For the sake of completeness, here's a working script with the changes mentioned below:

use warnings; use strict; use XML::LibXML; my $doc = XML::LibXML->load_xml( location => 'example.xhtml', no_network=>1, recover=>1 ); my $xpc = XML::LibXML::XPathContext->new($doc); $xpc->registerNs('html', 'http://www.w3.org/1999/xhtml'); my @ids2text = map { [ $_->getAttribute('id'), $_->textContent ] } $xpc->findnodes(q{//html:div[@class='data']}); $_->[1] =~ s/\W+//g for @ids2text; print join ", ", map sprintf("%s=%s", @$_), @ids2text;

</update>

Thanks very much for the reply! Your post inspired some more test cases for my file, and I'm sorry to say I broke your code :-( But here's the fix:

my @ids2text = map { [ $_->getAttribute('id'), $_->textContent ] } $doc->findnodes(q{//div[@class='data']});

Update: And yes, it does seem that load_html doesn't like XHTML - load_xml seems to work a bit better, although fetching the DTD from the net is pretty slow at the moment; adding the options {no_network=>1,recover=>1} disables the network check. However, with load_xml one also has to start using XML::LibXML::XPathContext:

my $xpc = XML::LibXML::XPathContext->new($doc); $xpc->registerNs('html', 'http://www.w3.org/1999/xhtml'); my @ids2text = map { [ $_->getAttribute('id'), $_->textContent ] } $xpc->findnodes(q{//html:div[@class='data']});

Update 2: Even with network, XML::LibXML is still complaining about &nbsp; ("Entity 'nbsp' not defined"), I'm not entirely sure why yet, as it seems to be defined in the DTD... Update 3: The W3C Validator doesn't complain...


In reply to Re^2: Parsing HTML/XML with Regular Expressions (XML::LibXML; updated!) by haukex
in thread Parsing HTML/XML with Regular Expressions by haukex

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.