在Perl中使用LibXML缩进子节点

时间:2015-02-03 03:37:32

标签: perl indentation libxml2 children

使用XML附加childNodes时,我在维护缩进时遇到了困难。

例如,如果我有以下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>

这段代码:

#!/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");

我得到了这个输出:

<?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>

我希望得到这个:

<?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>

我不想使用LibXML Pretty Print,因为它会更改XML的整个布局。我知道它在技术上都是一样的,但我试图尽可能避免空白差异。

由于

1 个答案:

答案 0 :(得分:1)

  

我不想使用LibXML Pretty Print

漂亮的打印是最好的方式。替代方案是:

  • 抓住位于&lt; plurals&gt;末尾的文本节点(现在在你的新项目之前),以前是换行符和4个空格,并将其更改为换行符和8个空格
  • 在新项目后添加文本节点,并为其指定换行符和4个空格

但是如果您的XML被移动并改变深度,那么这些数字(4/8)将会改变。这是一种非常适合打印的东西(以及no_blanks解析),旨在为您处理。