1

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>
4

2 回答 2

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');
于 2013-08-14T10:23:00.593 回答
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;
  } 
于 2013-08-14T11:50:36.493 回答