I am new to XML::Twig. How can I change all empty elements to use empty-element tags (<foo/>) instead of a start-tag and end-tag combo (<foo></foo>)?
Input:
<book>
<given-names>Maurice<xref ref-type="fn" rid="fnI_1"></xref></given-names>
<colspec colname="col1" colnum="1"></colspec>
<entry align="left"><p></p></entry>
</book>
I need output as:
<book>
<given-names>Maurice<xref ref-type="fn" rid="fnI_1"/></given-names>
<colspec colname="col1" colnum="1"/>
<entry align="left"><p/></entry>
</book>
I tried:
use XML::Twig;
my $xml = XML::Twig->new(twig_handlers => {
'xref' => sub {$_->set_tag('#EMPTY'),},
},
pretty_print => 'indented',
);
$xml->parse('sample.xml');
$xml->print;
}
But I can’t process it. How can change gloabally without content tag to empty tag? how can I change?
If you want to stick with Twig, you can do it like this:
Basically you have to manually check if the element contains nothing, then set it to be an empty element.