使用Perl XMLDOM解析器从具有相同属性的XML获取getValue

时间:2022-09-20 12:16:26

I am trying to get the value of 'TaxAmount' from the below XML which contains same tag name at different places.

我试图从下面的XML中获取'TaxAmount'的值,该XML在不同的地方包含相同的标记名称。

From the below XML, I want to get the value of 'TaxAmount' as '7.2' under tag 'Order', but I'm always getting the 'TaxAmount' as '1.2' under tag 'OrderItem' in 'OrderItemList'.

从下面的XML中,我想在'Order'标签下获得'TaxAmount'的值为'7.2',但我总是在'OrderItemList'的标签'OrderItem'下将'TaxAmount'作为'1.2'。

Could any one help me on getting the value of 'TaxAmount' as '7.2'?

任何人都可以帮我把'TaxAmount'的价值变成'7.2'吗?

I tried many things from other similar questions, but not succeeded in any.

我从其他类似的问题中尝试了很多东西,但没有成功。

<Order>
  <CustomerID />
  <IsCustomerCompany>false</IsCustomerCompany>
  <OrderTimezone />
  <OrderDescription />
  <OrderItemList>
    <OrderItem>
      <OrderItemID>1234</OrderItemID>
      <ItemCode />     
      <TaxAmount>6.0</TaxAmount>
    </OrderItem>
    <OrderItem>
      <OrderItemID>1245</OrderItemID>
      <ItemCode />
      <TaxAmount>1.2</TaxAmount>
    </OrderItem>
  </OrderItemList>
  <Currency>USD</Currency>
  <Amount>120</Amount>
  <TaxAmount>7.2</TaxAmount>
</Order>

The piece of code I'm using is,

我正在使用的代码是,

use XML::DOM;

$xml = XML::DOM::Parser->new->parse( $self->fullresponse )->getDocumentElement;
my $order_tag = $xml->tag('Order');
my $tax_amount =  $order_tag->getValue('TaxAmount');

Any help is appreciated.

任何帮助表示赞赏。

1 个解决方案

#1


Can't say for specific about the module you're using, but this will do the trick:

不能具体说明您正在使用的模块,但这样做可以解决问题:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig -> new (  ) -> parse ( 'your_xml_file' );
print $twig -> root -> get_xpath ( "./TaxAmount",0 ) -> text;

Note that in this example, your "root" node is Order so looking for Order beneath that is probably what's tripping you up.

请注意,在此示例中,您的“根”节点是Order,因此在下面查找Order可能会让您失望。

#1


Can't say for specific about the module you're using, but this will do the trick:

不能具体说明您正在使用的模块,但这样做可以解决问题:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

my $twig = XML::Twig -> new (  ) -> parse ( 'your_xml_file' );
print $twig -> root -> get_xpath ( "./TaxAmount",0 ) -> text;

Note that in this example, your "root" node is Order so looking for Order beneath that is probably what's tripping you up.

请注意,在此示例中,您的“根”节点是Order,因此在下面查找Order可能会让您失望。