Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
是否可以进一步简化XML::Simple生成的数据结构?_Xml_Perl - Fatal编程技术网

是否可以进一步简化XML::Simple生成的数据结构?

是否可以进一步简化XML::Simple生成的数据结构?,xml,perl,Xml,Perl,根据以下XML和脚本,我可以生成以下内容: { Item => { Details => { color => { Val => "green" }, texture => { Val => "smooth" } }, }, } 但是,我真的想要以下几点: { Item => { Details => { color => "green", texture => "smooth" }, }, } 我不

根据以下XML和脚本,我可以生成以下内容:

{
  Item => {
    Details => { color => { Val => "green" }, texture => { Val => "smooth" } },
  },
}
但是,我真的想要以下几点:

{
  Item => {
    Details => { color => "green", texture => "smooth" },
  },
}
我不能在这里使用GroupTags,因为可能有许多详细信息项Key/Val对,它们在处理之前可能是未知的。是否可以在不借助XPath、SAX等手动提取的情况下生成所需的结构

use strict;
use warnings;
use Data::Dump;
use XML::Simple;


my $xml = do { local $/; scalar <DATA> };
my $obj = XMLin(
    $xml,
    NoAttr     => 1,
    GroupTags  => { Details => 'Item' },
    KeyAttr => [ 'Key'],
);
dd($obj);
exit;

__END__
<?xml version="1.0" encoding="UTF-8"?>
<List attr="ignore">
    <Item attr="ignore">
        <Details attr="ignore">
            <Item attr="ignore">
                <Key>color</Key>
                <Val>green</Val>
            </Item>
            <Item attr="ignore">
                <Key>texture</Key>
                <Val>smooth</Val>
            </Item>
        </Details>
    </Item>
</List>
添加ContentKey参数:

my $obj = XMLin(
    $xml,
    NoAttr     => 1,
    GroupTags  => { Details => 'Item' },
    KeyAttr    => [ 'Key'],
    ContentKey => '-Val',
);
输出:

{ Item => { Details => { color => "green", texture => "smooth" } }, } 将解析为:

{ 'one' => 1, 'text' => 'Text' }
而不是:

{ 'one' => 1, 'content' => 'Text' }
将hashref转换为XML时,XMLout还将尊重此选项的值

您还可以使用“-”字符作为所选键名的前缀,让XMLin在数组折叠后更努力地消除不必要的“内容”键

{ 'one' => 1, 'content' => 'Text' }