0

I'm trying to build XML that looks like this using XML::Simple:

<response>
    <device>
        <interface>
            <mh>0x123abc</mh>
            <portname>Gi1/1</portname>
        </interface>
        <interface>
            <mh>0x123abc</mh>
            <portname>Gi1/1</portname>
        </interface>
        <interface>
            <mh>0x123abc</mh>
            <portname>Gi1/1</portname>
        </interface>
    </device>
</response>

I'm finding XML::Simple very difficult to behave like I want, so I tried feeding it it's own medicine:

$req = <<EOF;
<response>
    <device>
        <interface>
            <mh>0x123abc</mh>
            <portname>Gi1/1</portname>
        </interface>
        <interface>
            <mh>0x123abc</mh>
            <portname>Gi1/1</portname>
        </interface>
        <interface>
            <mh>0x123abc</mh>
            <portname>Gi1/1</portname>
        </interface>
    </device>
</response>
EOF
print Dumper(XML::Simple::XMLin($req));

yields:

$VAR1 = {
          'device' => {
                      'interface' => [
                                     {
                                       'portname' => 'Gi1/1',
                                       'mh' => '0x123abc'
                                     },
                                     {
                                       'portname' => 'Gi1/1',
                                       'mh' => '0x123abc'
                                     },
                                     {
                                       'mh' => '0x123abc',
                                       'portname' => 'Gi1/1'
                                     }
                                   ]
                    }
        };

If I feed that back into XML::Simple and print it:

my $xml = XML::Simple::XMLout($VAR1, RootName => "response");
print $xml;

I get this, which doesn't match what I sent it in the first place:

<response>
  <device>
    <interface mh="0x123abc" portname="Gi1/1" />
    <interface mh="0x123abc" portname="Gi1/1" />
    <interface mh="0x123abc" portname="Gi1/1" />
  </device>
</response>

How do I tell XML::Simple to treat a node as a node and not an attribute?

4

1 回答 1

4

一种选择是XML::Simple NoAttr

NoAttr => 1 # in+out - 方便

当与 XMLout() 一起使用时,生成的 XML 将不包含任何属性。所有哈希键/值都将表示为嵌套元素。

当与 XMLin() 一起使用时,XML 中的任何属性都将被忽略。

但是,从文档中XML::Simple

本模块的状态

不鼓励在新代码中使用此模块。其他模块也可以提供更直接和一致的接口。特别是,强烈推荐使用 XML::LibXML。

这个模块的主要问题是大量的选项以及这些选项交互的任意方式——通常会产生意想不到的结果。

欢迎使用带有错误修复和文档修复的补丁,但不太可能添加新功能。

因此,我强烈建议您使用其中一个XML::LibXMLXML::Twig因为您现在面临的问题。

相信我们。即使此解决方案确实有效,这也可能是众多解决方案中的第一个。

于 2014-10-01T15:59:13.090 回答