0

我试图在现有 XML 文件的某个 xpath 下添加一个内容块。我不熟悉使用 Perl 进行这种 XML 解析。但我应该使用这个XML::Twig

输入 :

  <model name="MDL_#USER#" oid="#LOOP#">
<appli name="ERETAIL" oid="2">
    <schema desc="Parameters schema" enab="YES" name="Parameters" oid="1" prio="1">
        <bean enab="YES" labl="Parameters" name="ERETAILPARA" oid="3" vers="1.0" xpos="0" ypos="0">
            <para>
                <root>
                    <row desc="password encryption mode" name="OISENCRYPT" value="BASE64"/>
                </root>
            </para>         
        </bean>
    </schema>
</appli>

输出:

   <model name="MDL_#USER#" oid="#LOOP#">
<appli name="ERETAIL" oid="2">
    <schema desc="Parameters schema" enab="YES" name="Parameters" oid="1" prio="1">
        <bean enab="YES" labl="Parameters" name="ERETAILPARA" oid="3" vers="1.0" xpos="0" ypos="0">
            <para>
                <root>
                    <row desc="password encryption mode" name="OISENCRYPT" value="BASE64"/>
                    <row name="INTERNAL" desc="" value="">
                        <row name="PATH" desc="Path" value="#PATH#" />
                        <row name="EXT" desc="Adresse" value="#GAIAIP#" />
                    </row>  
                </root>
            </para>         
        </bean>
    </schema>
</appli>

4

1 回答 1

2

对于XML::Twig,创建一个处理程序来修改要更改的元素。在该处理程序中,创建所需的新元素,然后将它们作为子元素粘贴到元素中:

use XML::Twig;

my $xml = <<'HERE';
<model name="MDL_#USER#" oid="#LOOP#">
<appli name="ERETAIL" oid="2">
    <schema desc="Parameters schema" enab="YES" name="Parameters" oid="1" prio="1">
        <bean enab="YES" labl="Parameters" name="ERETAILPARA" oid="3" vers="1.0" xpos="0" ypos="0">
            <para>
                <root>
                    <row desc="password encryption mode" name="OISENCRYPT" value="BASE64"/>
                </root>
            </para>         
        </bean>
    </schema>
</appli>
</model>
HERE

my $twig = XML::Twig->new(
    twig_handlers => {
        'bean/para/root' => \&add_rows,
        },
    pretty_print => 'indented',
    );
$twig->parse( $xml );
$twig->print;

请记住,在处理程序中,您将当前元素获取为$_

sub add_rows {
    XML::Twig::Elt->new( row => {
        name  => 'PATH',
        desc  => 'Path',
        value => '#PATH#'
        } )->paste( last_child => $_ );

    XML::Twig::Elt->new( row => {
        name  => 'EXT',
        desc  => 'Adresse',
        value => '#GAIAIP#'
        } )->paste( last_child => $_ );
    }
于 2012-08-17T05:34:57.127 回答