0

Perl 脚本读取 property.xml 并创建 install.properties 文件

如何读取多行并拆分 keyName 和 keyValue

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

open my $fh, '<', "property.xml"  or die "property.xml: $!";
open(CTS,">install.properties") or die $!;

while ( my $line = <$fh> ) {

if ($line =~ m/\<entry.*\<\/entry\>$/i ){     # how to read multiple line
my ($keyName, $keyValue) = split(//, $line);     # how to split 
print CTS $keyName = $keyValue;
}
}

属性.xml

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

安装.properties

TYPE = Rel
LOCATION = C:/Rel-LOCATION
HOST = localhost
4

3 回答 3

2

以下是使用 XML::Twig 执行此操作的方法,其中包含一些现代习语:

#!/usr/bin/perl

use strict;
use warnings;

use autodie qw( open); # dies with error message when open fails

use XML::Twig;

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

open( my $cts, '>', $OUT); # avoid "bareword filehandles" (CTS), use 3 arg open

XML::Twig->new( twig_handlers => { entry => \&entry, },)
         ->parsefile( $IN);

sub entry
  { my( $t, $entry)= @_;
    print {$cts} $entry->att( 'key'), " = ", $entry->trimmed_text, "\n"; 
  } 
于 2013-08-14T07:12:46.250 回答
2

我会使用 XML::LibXML 编写类似这样的代码。

use strict;
use warnings;
use feature 'say';
use XML::LibXML;

# Parse the XML
my $xml = XML::LibXML->load_xml(location => 'test.xml');

# Iterate the entries
for my $entry ($xml->findnodes('/properties/entry')) {

    my $key = $entry->findvalue('@key');

    # trim the value
    s/\A\s*//, s/\s*\z// for my $value = $entry->textContent;

    say "$key = $value";
}

该语句s/\A\s*//, s/\s*\z// for my $value = $entry->textContent

my $value = $entry->textContent;
$value =~ s/\A\s*//;
$value =~ s/\s*\z//;

替换进行修剪;\A锚点在字符串的开头,\z结尾(大致相当于^$resp。)。

say功能从 perl5 v10 开始可用,并提供say类似 的功能print,但附加一个换行符。

简单的 XPath 表达式的工作方式与文件路径类似,但@key会选择一个属性。

我在这里使用的各种 DOM 节点方法是:

  • findnodes– 获取与 XPath 表达式匹配的节点列表。
  • findvalue– 获取与 XPath 匹配的节点,并返回文本值。
  • textContent– 返回文本节点的值。
于 2013-08-14T07:04:18.490 回答
0

尝试XML::Simple我一直以来最喜欢的“XML 解析器”,用于简单的 XML 处理。它将您的文件加载到一个准备好使用的 perl 哈希/哈希数组/...数组中:-

use XML::Simple;
use Data::Dumper;

my $ref = XMLin('test.xml'); # load the file
print STDERR Dumper($ref);   # see how it looks
foreach my $k (keys %{$ref->{entry}}) # output to conf
{
    $v = $ref->{entry}->{$k}->{content};
    print "$k=$v\n";
}

效果很好:-

% perl test.pl

HOST=
    localhost

LOCATION=
    C:\Rel-LOCATION

TYPE=
    Rel

我已经为你留下了修剪等:)

于 2013-08-14T06:25:38.950 回答