Properly formatted xml requires a single root element. When XML::Twig attempts to parse your file, it finds the first div and decides that is the root element of the file. When it reaches the end of that and finds another tag at line 6, it gets unhappy and rightfully says there's an error.
If this document is actually intended to be XML, you'll need to enclose that data in fake element in order for it to be parsable. The following does that:
use strict;
use warnings;
use XML::Twig;
my $data = do {local $/; <DATA>};
# Enclose $data in a fake <root> element
$data = qq{<root>$data</root>};
my $twig = XML::Twig->new(
pretty_print => 'indented',
twig_handlers => {
association => sub {
$_->findnodes('div');
$_->set_att(name => 'xxx');
},
},
);
$twig->parse($data);
$twig->print;
__DATA__
<div
name="test1"
booktype="book1"
price="e200"
/>
<div
name="test2"
booktype="book2"
price="100" />
Outputs:
<root>
<div booktype="book1" name="test1" price="e200"/>
<div booktype="book2" name="test2" price="100"/>
</root>
Now, it's also unclear what you're trying to do with your "XML". I suspect you're trying to change the name attributes of the div tags to be 'xxx'. If that's the case then you need to redo your twig_handlers to the following:
twig_handlers => {
'//div' => sub { $_->set_att(name => 'xxx'); },
},
The output will then be:
<root>
<div booktype="book1" name="xxx" price="e200"/>
<div booktype="book2" name="xxx" price="100"/>
</root>
divelements without a root element, so it isn't well-formed XML. Please would you show something closer to the real problem?use strictanduse warningsat the start of every Perl program, especially when you are asking for help with your code