Пожалуйста - не используйте sed
- это не подходящий инструмент для работы.
Я бы сам использовал perl:
#!/usr/bin/env perl
use strict;
use warnings;
use XML::Twig;
my $twig = XML::Twig->new( 'pretty_print' => 'indented_a' );
$twig->parsefile ( 'your_file.xml' );
foreach my $thing ( $twig -> root -> children ) {
my $newthing = $twig -> root -> insert_new_elt($thing->tag);
foreach my $key ( keys %{$thing -> atts()} ) {
$newthing -> insert_new_elt($key, $thing -> att($key));
}
$thing -> delete;
}
$twig->print;
Вывод:
<root>
<book>
<pages>350</pages>
<name>Data Structure</name>
<price>250</price>
</book>
</root>
Это довольно просто, потому что мы работаем с (анонимным) хешем att ()
. Чтобы выбрать один атрибут, нам нужно сделать немного больше - нам нужно определить, что мы хотим сохранить name
, и вставить это как атрибут нашего родительского элемента.
Здесь используется карта
, что может быть немного головной болью:
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use XML::Twig;
my %keep_att = ( name => 1 );
my $twig = XML::Twig->new( 'pretty_print' => 'indented_a' );
$twig->parse( \*DATA );
foreach my $thing ( $twig->root->children ) {
my $newthing = $twig->root->insert_new_elt( $thing->tag,
{ map { $_ => $thing->att($_) } keys %keep_att } );
foreach my $key ( keys %{ $thing->atts() } ) {
next if $keep_att{$key};
$newthing->insert_new_elt( $key, $thing->att($key) );
}
$thing->delete;
}
$twig->print;
__DATA__
<root>
<book name="Data Structure" price="250" pages="350"/>
</root>
Это дает:
<root>
<book name="Data Structure">
<price>250</price>
<pages>350</pages>
</book>
</root>
Теперь, что происходит с этой картой
, мы в основном разделяем извлекаем атрибуты, которые мы хотим сохранить - и повторно вставляем их в наш новый элемент - и элементы, которые мы не хотим сохранять, и превращаем их в дочерние элементы.
Примерно так:
foreach my $thing ( $twig->root->children ) {
my %attributes = %{$thing->atts()};
my %new_children;
foreach my $attr ( keys %attributes ) {
if ( $keep_att{$attr} ) {
#leave it in %attributes;
}
else {
$new_children{$attr} = $attributes{$attr};
delete $attributes{$attr}
}
}
print Dumper \%attributes;
print Dumper \%new_children;
my $newthing = $twig->root->insert_new_elt( $thing->tag,
{ %attributes } );
foreach my $key ( keys %new_children ) {
$newthing->insert_new_elt( $key, $new_children{$key} );
}
$thing->delete;
}