cdm
cdm

Reputation: 799

Indentation of child nodes using LibXML in Perl

I'm having difficulty maintaining indentation when appending childNodes using XML.

For example, if I have the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<resources>

    <plurals name="number_of_items_selected">
        <item quantity="one">%1$d selected</item>
        <item quantity="other">%1$d selected</item>
    </plurals>

</resources>

And this code:

#!/usr/bin/perl

use XML::LibXML;
use strict;

my $parser = XML::LibXML->new;
my $dom = $parser->parse_file("plurals.xml") or die;

my @plurals = $dom->getElementsByTagName("plurals");
foreach my $plural (@plurals){
    my $tag = $dom->createElement("item");
    $tag->setAttribute('quantity'=>'many');
    $tag->appendText("many items selected");
    $plural->appendChild($tag);
}
$dom->toFile("plurals.xml");

I get this output:

<?xml version="1.0" encoding="UTF-8"?>
<resources>

    <plurals name="number_of_items_selected">
        <item quantity="one">%1$d selected</item>
        <item quantity="other">%1$d selected</item>
    <item quantity="many">many items selected</item></plurals>

</resources>

Whereas I want to get this:

<?xml version="1.0" encoding="UTF-8"?>
<resources>

    <plurals name="number_of_items_selected">
        <item quantity="one">%1$d selected</item>
        <item quantity="other">%1$d selected</item>
        <item quantity="many">many items selected</item>
    </plurals>

</resources>

I don't want to use LibXML Pretty Print because it changes the entire layout of the XML. I know that it's all technically the same, but I'm trying to avoid whitespace diff if possible.

Thanks

Upvotes: 1

Views: 284

Answers (1)

Jason Viers
Jason Viers

Reputation: 1762

I don't want to use LibXML Pretty Print

Pretty Print is the best way to go. The alternative is:

  • Grab the text node that was at the end of <plurals> (and is now before your new item), which was previously a newline and 4 spaces, and change it to a newline and 8 spaces
  • Add a text node after your new item, and give it a newline and 4 spaces

But those numbers (4/8) will change if your XML ever gets moved around and changes depth. This is the kind of stuff that pretty print (along with no_blanks parsing) is designed to handle for you.

Upvotes: 1

Related Questions