我希望将WSMAN提供的XML输出分解为多个XML文件,以便解析输出。
WSMAN给我的输出如下所示,它基本上有两个不同的XML文件,每个文件都有自己的根节点:
<?xml version="1.0" encoding="UTF-8"?>
<s:Body>
<wsen:PullResponse>
<wsen:Items>
<n1:DCIM_SoftwareIdentity>
<n1:ComponentType>BIOS</n1:ComponentType>
<n1:InstanceID>DCIM:CURRENT#741__BIOS.Setup.1-1</n1:InstanceID>
<n1:VersionString>1.3.6</n1:VersionString>
</n1:DCIM_SoftwareIdentity>
</wsen:Items>
</wsen:PullResponse>
</s:Body>
<?xml version="1.0" encoding="UTF-8"?>
<s:Body>
<wsen:PullResponse>
<wsen:Items>
<n1:DCIM_SoftwareIdentity>
<n1:ComponentType>BIOS</n1:ComponentType>
<n1:InstanceID>DCIM:INSTALLED#741__BIOS.Setup.1-1</n1:InstanceID>
<n1:VersionString>1.3.6</n1:VersionString>
</n1:DCIM_SoftwareIdentity>
</wsen:Items>
</wsen:PullResponse>
</s:Body>我不能用XML::Simple解析上面的输出,因为上面的输出包含两个根元素,就XML而言,这是“垃圾”。
Question/Statement:
我想将上面的输出分成两个不同的XML文件,每个文件都包含自己的根元素,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<s:Body>
<wsen:PullResponse>
<wsen:Items>
<n1:DCIM_SoftwareIdentity>
<n1:ComponentType>BIOS</n1:ComponentType>
<n1:InstanceID>DCIM:CURRENT#741__BIOS.Setup.1-1</n1:InstanceID>
<n1:VersionString>1.3.6</n1:VersionString>
</n1:DCIM_SoftwareIdentity>
</wsen:Items>
</wsen:PullResponse>
</s:Body>.
<?xml version="1.0" encoding="UTF-8"?>
<s:Body>
<wsen:PullResponse>
<wsen:Items>
<n1:DCIM_SoftwareIdentity>
<n1:ComponentType>BIOS</n1:ComponentType>
<n1:InstanceID>DCIM:INSTALLED#741__BIOS.Setup.1-1</n1:InstanceID>
<n1:VersionString>1.3.6</n1:VersionString>
</n1:DCIM_SoftwareIdentity>
</wsen:Items>
</wsen:PullResponse>
</s:Body>我的逻辑:
1)逐行分析输出
2)如果遇到?xml version模式,那么创建一个新的?xml version文件并将?xml version行和更多行写入这个新文件,直到再次遇到?xml version模式。
3)每次遇到?xml version模式时都遵循步骤2
这是我的代码:
#!/usr/bin/perl -w
use strict;
use XML::Simple;
use Data::Dumper;
my $counter = 0;
my $fileName;
while (my $line = <DATA>)
{
if ( $line =~ /\?xml version/ )
{
$counter++;
print "Creating the BIOS file \n";
$fileName = "BIOS"."_".$counter;
}
open (my $sub_xml_file, ">" , $fileName) or die "Canot create $fileName: $!\n";
print $sub_xml_file $line;
}
__DATA__
## omitting this part as this contains the XML info listed above.现在,我的脚本确实创建了BIOS_1和BIOS_2文件,但它只向它写入了上面的最后一行XML输出:
# cat BIOS_1
</s:Body>
# cat BIOS_2
</s:Body>你能帮我修复我的脚本来创建两个不同的XML文件吗..。
发布于 2013-02-22 10:58:41
您永远不会为以后的循环传递保留$line。
在内存方法中加载所有内容:
my $count;
my $file; { local $/; $file = <>; }
for my $xml (split /^(?=<\?xml)/m, $file) {
my $fn = sprintf("BIOS_%d.xml", ++$count);
open(my $fh, '>', $fn) or die $!;
print $fh $xml;
}按时间顺序排列:
my $fh;
my $count;
while (<>) {
if (/^<\?xml/) {
my $fn = sprintf("BIOS_%d.xml", ++$count);
open($fh, '>', $fn) or die $!;
}
print $fh $_;
}https://stackoverflow.com/questions/15022371
复制相似问题