In general, whitespace in XML is considered significant. OK, in many dialects of XML nobody cares about whitespace, but because it does matter in some XML dialects, general XML tools (such as XML::LibXML) will not insert whitespace for you.
Firstly, you should ask yourself, do you care about indenting and pretty formatting the XML? I agree that it's nice to have, but do you want it at the cost of potentially complicating and slowing down your code?
In some cases the answer to this is no. If the XML is only ever going to be processed by scripts, then it doesn't matter what it looks like, as long as it works.
In other cases, you know that the XML you're generating is likely to be read and edited by humans with text editors. So slowing your code down and complicating it might be worth the pay-off.
If you decide that you don't care about whitespace, then you're done. Your code is working fine.
If you do care about whitespace, you've got two alternative solutions:
The first option will keep your code running roughly at the current speed, but litters your code with junk that is likely to make it less maintainable.
The second option is likely to slow down your script somewhat (though with small files like the one you give as an example, negligibly) but doesn't clutter your code as much.
One module that can prettify your XML is XML::LibXML::PrettyPrint. There are others, but I personally think it's the best of the bunch. (Though I did write it, so I would!) Here's how you'd change your code to use it... Replace this:
$doc->toFile($file,1);With this:
require XML::LibXML::PrettyPrint; XML::LibXML::PrettyPrint -> new( element => {inline=>['name']} ) -> pretty_print($doc) -> toFile($file);
Setting name as an inline element ensures that your output is formatted like this:
<configuration> <property> <name>test1</name> </property> <property> <name>test2</name> </property> </configuration>
The default (without making any elements inline) would have been like this:
<configuration> <property> <name> test1 </name> </property> <property> <name> test2 </name> </property> </configuration>
Using the defaults allows you to simplify your code even more though:
require XML::LibXML::PrettyPrint; XML::LibXML::PrettyPrint->pretty_print($doc)->toFile($file);
In reply to Re: Problem to add xml element in a formatted structure
by tobyink
in thread Problem to add xml element in a formatted structure
by gdanenb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |