Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove the <opt> tag in XML::Simple output?

Tags:

xml

ruby

perl

I'm creating an XML file using Perl and XML::Simple module. I successfully create the XML file, but the problem is I am having <opt> </opt> tag for each my tags. I am looking for any option which we can aviod the <opt> </opt> tag. I can't do the post-processing to remove the tag. because the file size is huge.

Example :

<opt>
  <person firstname="Joe" lastname="Smith">
    <email>[email protected]</email>
    <email>[email protected]</email>
  </person>
  <person firstname="Bob" lastname="Smith">
    <email>[email protected]</email>
  </person>
</opt>

and I am looking for (without <opt> tag):

  <person firstname="Joe" lastname="Smith">
    <email>[email protected]</email>
    <email>[email protected]</email>
  </person>
  <person firstname="Bob" lastname="Smith">
    <email>[email protected]</email>
  </person>
like image 904
joe Avatar asked Dec 10 '22 20:12

joe


2 Answers

The tag is the root element of the XML generated from the user-supplied data-structure. From the XML::Simple documentation -

RootName => 'string' # out - handy

By default, when XMLout() generates XML, the root element will be named 'opt'. This option allows you to specify an alternative name.

Specifying either undef or the empty string for the RootName option will produce XML with no root elements. In most cases the resulting XML fragment will not be 'well formed' and therefore could not be read back in by XMLin(). Nevertheless, the option has been found to be useful in certain circumstances.

To set the root element to blank just pass RootName as 'undef' to XMLout, for eg.

use XML::Simple;

my $xml = XMLout($hashref, RootName => undef);
like image 143
aks Avatar answered Dec 27 '22 19:12

aks


I came across this answer when searching for the same info (read, parse, modify, and output xml, fix the <opt> root tag) but in Ruby.

FYI, the root node can also be removed or named in the Ruby version of the library:

require 'xmlsimple' # gem install xml-simple
data = XmlSimple.xml_in(filename)  # read data from filename
# Parse data as needed, then output:
XmlSimple.xml_out(data, { 'RootName' => nil })     # Remove root element
XmlSimple.xml_out(data, { 'RootName' => 'html' })  # Change root <opt> to <html>
like image 38
Jeff Ward Avatar answered Dec 27 '22 21:12

Jeff Ward