perl脚本使用XML解析器读取文本文件中的值并将其替换为xml文件

时间:2013-08-14 10:11:24

标签: perl

Perl脚本使用XML解析器读取文本文件中的值并将其替换为xml文件

如何读取xml标记并从文本文件值中替换值。如果install.properties中的条目值为null,则必须在property.xml中更新,并且如果条目值为null xml,则应使用文本文件值更新

install.properties文本文件

TYPE = Patch
LOCATION = 
HOST = 127.1.1.1
PORT = 8080
替换值之前的

property.xml文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="TYPE">Release</entry>
    <!-- tst  -->
    <entry key="LOCATION">c:/release</entry>
    <entry key="HOST">localhost</entry>    
    <entry key="PORT"></entry>    

</properties>
更换值后的

property.xml文件

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="TYPE">Patch</entry>
    <!-- tst  -->
    <entry key="LOCATION"></entry>
    <entry key="HOST">127.1.1.1</entry>    
    <entry key="PORT">8080</entry>    

</properties>

2 个答案:

答案 0 :(得分:6)

使用XML::XSH2的解决方案,XML::LibXML的包装。

#!/usr/bin/perl
use warnings;
use strict;

use XML::XSH2;

open my $INS, '<', 'install.properties' or die $!;

while (<$INS>) {
    chomp;
    my ($var, $val) = split / = /;        # / fix StackOverflow syntax highlighting.
    $XML::XSH2::Map::ins->{$var} = $val;
}

xsh << '__XSH__';
open property.xml ;
for /properties/entry {
    set ./text() xsh:lookup('ins', @key) ;
}
save :b ;
__XSH__

仅使用XML::LibXML创建的相同程序:

#!/usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

open my $INS, '<', 'install.properties' or die $!;

my %ins;
while (<$INS>) {
    chomp;
    my ($var, $val) = split / = /;  # / fix StackOverflow syntax highlighting.
    $ins{$var} = $val;
}

my $xml = 'XML::LibXML'->load_xml( location => 'property.xml' );
for my $entry( $xml->findnodes('/properties/entry')) {
    my ($text) = $entry->findnodes('text()');
    $text->setData($ins{ $entry->getAttribute('key') });
}
rename 'property.xml', 'property.xml~';
$xml->toFile('property.xml');

答案 1 :(得分:1)

再次,使用XML :: Twig:

#!/usr/bin/perl

use strict;
use warnings;

use autodie qw( open);

use XML::Twig;

my $IN= "install.properties";
my $XML= "properties.xml";

# load the input file into a a hash key => value
open( my $in, '<', $IN);
my %entry= map { chomp; split /\s*=\s*/; } <$in>;


XML::Twig->new( twig_handlers => { entry => \&entry, },
                keep_spaces => 1,
              )
         ->parsefile_inplace( $XML);

 sub entry
  { my( $t, $entry)= @_;
    if( my $val= $entry{$entry->att( 'key')} )
      { $entry->set_text( $val); }
    $t->flush;
  }