如何使用在xml文件中追加一行?

时间:2013-12-11 06:16:58

标签: xml perl

输入:

<?xml version='1.0'?>
<root>
<category cname='Cname1' id='c1'>
  <subcat key='3' sname='Subname1' sid='sid1'>
    <prod key='1' pname='Productname'>value1</prod>
  </subcat>
</category>
</root>

输出应在下面提到:

<?xml version='1.0'?>
    <root>
    <category cname='Cname1' id='c1'>
      <subcat key='3' sname='Subname1' sid='sid1'>
        <prod key='1' pname='Productname'>value1</prod>
        **<prod key='2' pname='Productname1'>value2</prod>**
      </subcat>
    </category>
    </root>

我使用了File :: Slurp模块来附加这个。但我想使用Xml :: Simple或Xml :: Twig来获取此输出。

请帮我搞定。

先谢谢。

2 个答案:

答案 0 :(得分:1)

这样的东西?

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig->new(
  pretty_print  => 'indented',
  twig_handlers => {

    # When we get to the end of a <root> or <category> element,
    # output everything we've processed so far.
    'root|category'  => sub { $_[0]->flush },

    # When a <subcat> element is encountered...
    'subcat' => sub {
      # Create a new element
      my $new = XML::Twig::Elt->new(
        "prod",
        {
          key   => 1,
          pname => "Productname1",
        },
        "value2",
      );
      # Insert it at the end...
      $new->paste(after => $_->last_child);
    },
  },
);
$twig->parse(\*DATA);

__DATA__
<?xml version='1.0'?>
<root>
<category cname='Cname1' id='c1'>
  <subcat key='3' sname='Subname1' sid='sid1'>
   <prod key='1' pname='Productname'>value1</prod>
  </subcat>
</category>
</root>

答案 1 :(得分:0)

如果您已经拥有有关新产品的所有数据,包括应该在文件中插入的位置,我将如何操作:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $p= { category => 'Cname1', subcat => '3', 
         key => '2', pname => 'Productname1', value => 'value2'
       };

# XPath selecting the appropriate subcat
my $change= qq{category[\@cname="$p->{category}"]/subcat[\@key="$p->{subcat}"]};

XML::Twig->new( twig_handlers => { $change => sub { new_product( @_, $p); } },
                pretty_print => 'indented'
              )
          ->parsefile( 'products.xml')
          ->print;

sub new_product
  { my( $t, $subcat, $p)= @_;
    $subcat->insert_new_elt( last_child => prod => 
                              { pname => $p->{pname}, key => $p->{key} },
                              $p->{value}
                           );
  }