3

XML ファイル ( information.xml) があります。この XML ファイルから要素と属性の値を抽出し、それらの要素と属性の値を別の XML ファイル ( build.xml) に挿入する必要があります。build.xmlファイルから適切な要素の値とタグを入力して、ファイルを変更する必要がありinformation.xmlます。

そのためには、XML::LibXML を使用する必要があります。から要素と属性の値を抽出できますinformation.xml。しかし、私はそれらの値を開いて入力することができませんbuild.xml

例 :

information.xml

<info>
  <app version="10.5.10" long_name ="My Application">
    <name> MyApp </name>
    <owner>larry </owner>
    <description> This is my first application</description>
  </app>
</info>

build.xml

<build long_name="" version="">
  <section type="Appdesciption">
    <description> </description>
  </section>
  <section type="Appdetails">
    <app_name> </app_name>
    <owner></owner>
  </section>
</build>

ここで、私のタスクは、所有者の値を から抽出しinformation.xml、開いてbuild.xml、所有者タグを検索し、build.xmlそこに抽出された値を配置することです。

Perl スクリプトは次のようになります。

#!/usr/bin/perl
use strict;
use warnings;
use XML::LibXML;
my $file1="/root/shubhra/myapp/information.xml";
my $file2="/root/shubhra/myapp/build.xml";

my $parser = XML::LibXML->new();
my $doc = $parser->parse_file($file1);
foreach my $line ($doc->findnodes('//info/app'))
{
    my $owner= $line->findnodes('./owner');  # 1st way
    print "\n",$owner->to_literal,"\n";

    my ($long_name) = $line->findvalue('./@long_name');  # 2nd way
    print "\n $long_name \n";

    my $version = $line->findnodes('@version');
    print "\n",$version->to_literal,"\n";
}

my $parser2 = XML::LibXML->new();
my $doc2 = $parser2->parse_file($file2);
foreach my $line2 ($doc2->findnodes('//build'))
{
    my ($owner2)= $line2->findnodes('./section/owner/text()');

    my ($version2)=$line2->findvalue('./@version');

    print "\n Build.xml already has version : $version2 \n";
    print "\n Build.xml already has owner :",$owner2->to_literal;

    $owner2->setData("Windows Application 2"); # Not changing build.xml
    $line2->setAttribute(q|version|,"60.60.60");  # Not changing build.xml 
    my $changedversion = $line2->getAttribute(q|version|); 
    #superficially changed but didn't changed build.xml content
    print "\n The changed version is : $changedversion";
}

build.xml次のようになります:

<build long_name="" version="9.10.10">
<section type="Appdesciption">
<description> </description>
</section>
<section type="Appdetails">
<app_name> </app_name>
<owner>shubhra</owner>
</section>
</build>

my $doc3 = XML::LibXML->load_xml(location => $file2, no_blanks => 1);
my $xpath_expression = '/build/section/owner/text()';
my @nodes = $doc3->findnodes( $xpath_expression );
for my $node (@nodes) {
    my $content = $node->toString;
    $content = $owner;
    $node->setData($content);
}
$doc->toFile($file2 . '.new', 1);
4

1 に答える 1