XML :: LibXML,名称空间和findvalue [英] XML::LibXML, namespaces and findvalue

查看:82
本文介绍了XML :: LibXML,名称空间和findvalue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 XML::LibXML 来解析具有名称空间的XML文档.因此,我使用XPath //u:modelfindnodes使用 XML::LibXML::XPathContext findnodes.正确返回3个节点.

I'm using XML::LibXML to parse an XML document with a namespace. I therefore use XML::LibXML::XPathContext to findnodes using the XPath //u:model. This correctly returns 3 nodes.

我现在想对返回的3个 XML::LibXML::Element 对象,但无法确定有效的方法/xpath.或者,我迭代子节点并直接与nodeName匹配,但这不理想:

I now would like to use findvalue on the 3 returned XML::LibXML::Element objects, but am unable to determine a working method/xpath. As an alternative, I iterate on the children and match against the nodeName directly, but this is less than ideal:

use strict;
use warnings;

use XML::LibXML;
use XML::LibXML::XPathContext;

my $dom = XML::LibXML->load_xml( IO => \*DATA );
my $context = XML::LibXML::XPathContext->new( $dom->documentElement() );
$context->registerNs( 'u' => 'http://www.ca.com/spectrum/restful/schema/response' );

for my $node ( $context->findnodes('//u:model') ) {
    #my $mh = $node->findvalue('mh');
    my ($mh)
        = map { $_->textContent() }
        grep  { $_->nodeName() eq 'mh' } $node->childNodes();

    #my $attr = $node->findvalue('attribute');
    my ($attr)
        = map { $_->textContent() }
        grep  { $_->nodeName() eq 'attribute' } $node->childNodes();

    print "mh = $mh, attr = $attr\n";
}

__DATA__
<root xmlns="http://www.ca.com/spectrum/restful/schema/response">
  <error>EndOfResults</error>
  <throttle>86</throttle>
  <total-models>86</total-models>
  <model-responses>
    <model>
      <mh>0x100540</mh>
      <attribute id="0x1006e">wltvbswfc02</attribute>
    </model>
    <model>
      <mh>0x100c80</mh>
      <attribute id="0x1006e">wltvsutm1ds02</attribute>
    </model>
    <model>
      <mh>0x100c49</mh>
      <attribute id="0x1006e">wltvsdora03</attribute>
    </model>
  </model-responses>
</root>

胜利:

mh = 0x100540, attr = wltvbswfc02
mh = 0x100c80, attr = wltvsutm1ds02
mh = 0x100c49, attr = wltvsdora03

是否有一种方法可以使用注释掉的行来查找节点,而不是使用间接对子代进行迭代的方法?还是有另一种方法来解决这个问题以获得配对值?

Is there a way to use the commented out lines to find the nodes instead of the indirect method of iterating on the children? Or is there another way to approach this problem to get the paired values?

推荐答案

由于整个默认名称空间的原因,您不能使用$node->findvalue().但是,您可以重用XML :: LibXML :: XPathContext对象来查找所需的值:

You can't use $node->findvalue() because of the whole default namespace thing. However, you can reuse your XML::LibXML::XPathContext object to find the values you want:

for my $node ( $context->findnodes('//u:model') ) {
   my $mh   = $context->findvalue('u:mh', $node);
   my $attr = $context->findvalue('u:attribute', $node);
   print "mh = $mh, attr = $attr\n";
}

这篇关于XML :: LibXML,名称空间和findvalue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆