如何动态生成XML?

时间:2011-04-24 15:39:22

标签: xml perl xml-simple

我之前实际上曾问过this question in a different form。我确实得到了一个很好的答案,但我认为我需要更多的澄清,所以我再次以整体形式提出这个问题。

用户可以编写类似以下内容的脚本:

$ABC->Command(100, 100);
my $group  = "1";
my $id     = "1";
my $value1 = "Some Process A Happened";
$rep->getParameter($group, $id, $value1);
$ABC->Command(100, 100);
my $group  = "1";
my $id     = "2";
my $value1 = "Some Process B Happened";
$rep->getParameter($group, $id, $value1);
$ABC->Command(100, 100);
my $group  = "2";
my $id     = "1";
my $value1 = "Some Process A Happened";
$rep->getParameter($group, $id, $value1);
$ABC->Command(100, 100);
my $group  = "2";
my $id     = "1";
my $value1 = "Some Process Happened";
$rep->getParameter($group, $id, $value1);
$ABC->Command(100, 100);
my $group  = "3";
my $id     = "1";
my $value1 = "Some Process Happened";
$rep->getParameter($group, $id, $value1);
$ABC->SomeImage($image) $desc = "Some info";
$rep->getImage($image, $desc);
$rep->getResult("Pass")

这必须生成如下的XML:

<?xml version="1.0" encoding="UTF-8" ?>
<TestResult xmlns="http://test.com/automate" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://test.com/automate">
    <Result>Pass</Result>
    <Comments>Executed Successfully</Comments>
    <Parameters>
        <ParameterGroup ID="Group1">
            <Parameter key="Key1">Some Value</Parameter>
            <Parameter key="Key2">Some Value</Parameter>
            <Parameter key="Key3">Some Value</Parameter>
        </ParameterGroup>
        <ParameterGroup ID="Group2">
            <Parameter key="Key1">Some Value</Parameter>
            <Parameter key="Key2">Some Value</Parameter>
            <Parameter key="Key3">Some Value</Parameter>
        </ParameterGroup>
        <ParameterGroup ID="Group3">
            <Parameter key="Key1">Some Value</Parameter>
            <Parameter key="Key2">Some Value</Parameter>
            <Parameter key="Key3">Some Value</Parameter>
        </ParameterGroup>
    </Parameters>
    <Images>
        <Image key="ImageTag1">info</Image>
        <Image key="ImageTag2">info</Image>
        <Image key="ImageTag3">info</Image>
    </Images>
</TestResult>

将在不同的时间点输入图像值和参数值。但是它们必须被收集并放在Images元素内,类似于Parameters。我应该遵循什么方法?请一些代码示例。


编辑

我有类似

的东西
$xml = {
    ParameterGroup => [
        {
            ID        => 'Group1',
            Parameter => {
                Key1  => {content => 'Some Value'},
                Key2  => {content => 'Some Value'},
                Key3  => {content => 'Some Value'},
            },
        },
        {
            ID        => 'Group2',
            Parameter => {
                Key1  => {content => 'Some Value'},
                Key2  => {content => 'Some Value'},
                Key3  => {content => 'Some Value'},
            },
        },
    ]
};
print XMLout(
    $xml,
    RootName => 'Parameters',
    KeyAttr  => 'value',
);

作为结构,但这些是固定结构。如何使这种动态符合用户的要求?

2 个答案:

答案 0 :(得分:2)

考虑一下您的驱动程序代码下面的一些小调整。

#! /usr/bin/env perl

use warnings;
use strict;

use TestResult;

my $tr = TestResult->new;

$tr->parameter(1, 1, "Some Process A Happened");
$tr->parameter(1, 2, "Some Process B Happened");
$tr->parameter(2, 1, "Some Process A Happened");
$tr->parameter(3, 1, "Some Process Happened");

$tr->image(1, "Some info");

$tr->result("Pass");
$tr->comments("Executed Successfully");

print $tr->as_xml;

XML输出

<?xml version="1.0" encoding="UTF-8" ?>
<TestResult xmlns="http://test.com/automate" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://test.com/automate">
  <Result>Pass</Result>
  <Comments>Executed Successfully</Comments>
  <Parameters>
    <ParameterGroup ID="Group1">
      <Parameter key="Key1">Some Process A Happened</Parameter>
      <Parameter key="Key2">Some Process B Happened</Parameter>
    </ParameterGroup>
    <ParameterGroup ID="Group2">
      <Parameter key="Key1">Some Process A Happened</Parameter>
    </ParameterGroup>
    <ParameterGroup ID="Group3">
      <Parameter key="Key1">Some Process Happened</Parameter>
    </ParameterGroup>
  </Parameters>
  <Images>
    <Image key="ImageTag1">Some info</Image>
  </Images>
</TestResult>

查看$self->{_xml}内容的转储可能有助于您理解。

{
  'Comments' => { 'content' => 'Executed Successfully' },
  'Parameters' => {
    'ParameterGroup' => {
      'Group1' => {
        'Parameter' => {
          'Key2' => { 'content' => 'Some Process B Happened' },
          'Key1' => { 'content' => 'Some Process A Happened' }
        }
      },
      'Group3' => {
        'Parameter' => {
          'Key1' => { 'content' => 'Some Process Happened' }
        }
      },
      'Group2' => {
        'Parameter' => {
          'Key1' => { 'content' => 'Some Process A Happened' }
        }
      }
    }
  },
  'xmlns' => 'http://test.com/automate',
  'Result' => { 'content' => 'Pass' },
  'xmlns:xsi' => 'http://www.w3.org/2001/XMLSchema-instance',
  'xsi:schemaLocation' => 'http://test.com/automate',
  'Images' => {
    'ImageTag1' => { 'content' => 'Some info' }
  }
}

下面是让你到达的TestResult模块。请务必将其放在模块搜索路径中某个名为TestResult.pm的文件中。它以熟悉的样板开始。

package TestResult;

use strict;
use warnings;

use XML::Simple;

在编译时,我们设置了一个特定于所需XML格式的XML :: Simple子类,它将以适当的顺序输出元素。

BEGIN {
  @__PACKAGE__::XML::ISA = qw/ XML::Simple /;

  my %order = (
    TestResult => [qw/
      xmlns xmlns:xsi xsi:schemaLocation
      Result Comments Parameters Images
    /],
  );

  *__PACKAGE__::XML::sorted_keys = sub {
    my($self,$name,$h) = @_;
    return @{ $order{$name} } if $order{$name};
    sort keys %$h;
  };
}

每个实例都将携带输出文档的内容。硬编码的键值对成为TestResult元素的属性。

sub new {
  my($class) = @_;
  my $self = {
    _xml => {
      "xmlns"              => "http://test.com/automate",
      "xmlns:xsi"          => "http://www.w3.org/2001/XMLSchema-instance",
      "xsi:schemaLocation" => "http://test.com/automate",
    },
  };

  bless $self => $class;
}

commentsresult的实现很简单,因为它们生成的XML很简单。这些方法在相应的插槽中填充位,没有任何意外。

sub comments {
  my($self,$comments) = @_;
  $self->{_xml}{Comments} = { content => $comments };
}

sub result {
  my($self,$result) = @_;
  $self->{_xml}{Result} = { content => $result };
}

我们必须小心imageparameter,因为它们包含多个孩子。盲目地覆盖$self->{_xml}{Images}$self->{_xml}{Parameter}会破坏已经累积的任何内容,因此我们会逐步添加新元素。

sub image {
  my($self,$image,$desc) = @_;

  my $imageid = "ImageTag" . $image;
  $self->{_xml}{Images}{$imageid} = { content => $desc };
}

sub parameter {
  my($self,$group,$key,$value) = @_;

  my $groupid = "Group" . $group;
  my $keyid   = "Key"   . $key;

  $self->{_xml}{Parameters}{ParameterGroup}{$groupid}{Parameter}{$keyid} =
    { content => $value };
}

最后,我们使用TestResult :: XML对XML进行编码。 GroupTags参数声明嵌套关系,例如<Images>包含<Image>。 (首先,我尝试对<Parameters><ParameterGroup>之间以及<ParameterGroup><Parameter>之间的关系进行类似处理,但XML输出与您想要的不同。) KeyAttr参数告诉XML :: Simple使用Perl哈希键作为XML属性。如果您使用+读取其他工具生成的TestResults,XMLin前缀将获得更好的结果。

sub as_xml {
  my($self) = @_;

  my $serialize = __PACKAGE__::XML->new;

  $serialize->XMLout(
    $self->{_xml},
    GroupTags => {
      Images => "Image",
    },
    KeyAttr => {
      ParameterGroup => "+ID",
      Parameter      => "+key",
      Image          => "+key",
    },
    RootName => "TestResult",
    XMLDecl => '<?xml version="1.0" encoding="UTF-8" ?>',
  );
}

返回一个真值,表示模块已成功加载。

1;

答案 1 :(得分:1)

XML :: Simple希望您将输出组装成perl数据结构,然后将其转换为XML;您是否在实际调用生成XML时遇到问题,弄清楚数据结构应该是什么样的,或者用数据填充它? (或者完全不同的东西?)

打破你的问题,一次解决一下。