Frage

I have the following xml

<?xml version="1.0" encoding="utf-8"?>
<Response>
   <Function Name="GetSomethingById">
      <something idSome="1" Code="1" Description="TEST01" LEFT="0" RIGHT="750" />
   </Function>
</Response>

and I want the attributes of <something> node as a hash. Im trying like below

my $xpc = XML::LibXML::XPathContext->new(
    XML::LibXML->new()->parse_string($xml)   # $xml is containing the above xml
);
my @nodes = $xpc->findnodes('/Response/Function/something');

Im expecting to have something like $nodes[0]->getAttributes, any help?

War es hilfreich?

Lösung

my %attributes = map { $_->name => $_->value } $node->attributes();

Andere Tipps

Your XPATH query seems to be wrong - you are searching for '/WSApiResponse/Function/something' while the root node of your XML is Response and not WSApiResponse

From the docs of XML::LibXML::Node (the kind of stuff that findnodes() is expected to return), you should look for my $attrs = $nodes[0]->attributes() instead of $nodes[0]->getAttributes

I use XML::Simple for this type of thing. So if the XML file is data.xml

use strict;
use XML::Simple();
use Data::Dumper();

my $xml = XML::Simple::XMLin( "data.xml" );
print Data::Dumper::Dumper($xml);
my $href = $xml->{Function}->{something};
print Data::Dumper::Dumper($href);

Note: With XML::Simple the root tag maps to the result hash itself. Thus there is no $xml->{Response}

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top