读取property.xml并创建install.properties文件的Perl脚本
如何读取多行并拆分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;
}
}
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">
Rel
</entry>
<!-- tst -->
<entry key="LOCATION">
C:/Rel-LOCATION
</entry>
<entry key="HOST">
localhost
</entry>
</properties>
install.properties
TYPE = Rel
LOCATION = C:/Rel-LOCATION
HOST = localhost
答案 0 :(得分: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
在结尾处(大致相当于^
和$
。)
say
功能自perl5 v10开始提供,并提供say
功能,其功能类似print
,但附加换行符。
简单XPath表达式的工作方式与文件路径类似,但@key
选择属性。
我在这里使用的各种DOM节点方法是:
findnodes
- 获取与XPath表达式匹配的节点列表。findvalue
- 获取与XPath匹配的节点,并返回文本值。textContent
- 返回文本节点的值。答案 1 :(得分: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";
}
答案 2 :(得分: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
我已经离开了修剪等:)