Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl -w
- use strict;
- use Config::Augeas;
- use XML::LibXML;
- use Getopt::Long;
- my $file;
- my $root = '/';
- my $verbose;
- my $debug;
- my $result = GetOptions (
- "file=s" => \$file,
- "root=s" => \$root,
- "verbose" => \$verbose,
- "debug" => \$debug,
- );
- $verbose ||= $debug;
- unless (defined($file)) {
- die "E: You must specify a filename\n";
- }
- open (my $fh, "<$file") or die "E: Could not open $file: $!\n" ;
- my $doc = XML::LibXML->load_xml(IO => $fh);
- close $fh;
- my $aug = Config::Augeas->new(root => $root);
- # we want to replace everything
- $aug->rm('/files/*');
- my @top_nodes = $doc->find('/*/node[@label != "files"]')->get_nodelist();
- for my $node (@top_nodes) {
- xml2aug($node, '/files');
- }
- $aug->print('/files') if $debug;
- $aug->save();
- $aug->print('/augeas//error');
- ########
- # Subs
- ########
- sub xml2aug {
- my ($elem, $path) = @_;
- my $type = $elem->nodeType;
- my $label = $elem->getAttribute('label');
- my $matchpath = "$path/*[last()]";
- $matchpath =~ s| |\\ |g;
- my $lastpath = $aug->match("$path/*[last()]");
- if(defined($lastpath)) {
- print "V: Inserting $label after $lastpath\n" if $verbose;
- # Insert last node
- $aug->insert($label, "after", $lastpath);
- } else {
- $aug->set("$path/$label", '');
- }
- $matchpath = "$path/${label}[last()]";
- $matchpath =~ s| |\\ |g;
- my $newpath = $aug->match($matchpath);
- my $value;
- for my $child ($elem->childNodes()) {
- if ($child->nodeType == XML_TEXT_NODE) {
- # Text node
- $value = $child->nodeValue;
- } else {
- xml2aug($child, $newpath);
- }
- }
- if (defined($value)) {
- print "V: Setting value of $newpath to $value\n" if $verbose;
- $aug->set($newpath, $value);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement