鉴于以下XML和脚本,我可以生成:
{
Item => {
Details => { color => { Val => "green" }, texture => { Val => "smooth" } },
},
}
Run Code Online (Sandbox Code Playgroud)
但是,我真的想要以下内容:
{
Item => {
Details => { color => "green", texture => "smooth" },
},
}
Run Code Online (Sandbox Code Playgroud)
我不能在这里使用GroupTags,因为可能有许多Details项(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>
Run Code Online (Sandbox Code Playgroud)
添加ContentKey参数:
my $obj = XMLin(
$xml,
NoAttr => 1,
GroupTags => { Details => 'Item' },
KeyAttr => [ 'Key'],
ContentKey => '-Val',
);
Run Code Online (Sandbox Code Playgroud)
输出:
{
Item => { Details => { color => "green", texture => "smooth" } },
}
文档说明:
ContentKey => 'keyname'#in + out - 很少使用将文本内容解析为哈希值时,此选项允许您指定哈希键的名称以覆盖默认值
'content'.例如:Run Code Online (Sandbox Code Playgroud)XMLin('<opt one="1">Text</opt>', ContentKey => 'text')将解析为:
Run Code Online (Sandbox Code Playgroud){ 'one' => 1, 'text' => 'Text' }代替:
Run Code Online (Sandbox Code Playgroud){ 'one' => 1, 'content' => 'Text' }
XMLout在将hashref转换为XML时,也会尊重此选项的值.您还可以在选定的键名前加上一个
'-'字符,以便在阵列折叠后XMLin尝试更难以消除不必要的'content'键.
| 归档时间: |
|
| 查看次数: |
147 次 |
| 最近记录: |