加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xml – findnodes()中的xpath表达式返回空节点列表

发布时间:2020-12-16 23:31:07 所属栏目:百科 来源:网络整理
导读:XML: zoo xmlns="http://www.zoo.com" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:schemaLocation="http://www.zoo.com employee.xsd"area id="1" posizione="nord" nome="scimmie" animale nomeGigi/nome sessoMale/sesso eta3/eta /animal
XML:

<zoo xmlns="http://www.zoo.com" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:schemaLocation="http://www.zoo.com employee.xsd">

<area id="1" posizione="nord" nome="scimmie">
    <animale>
        <nome>Gigi</nome>
        <sesso>Male</sesso>
        <eta>3</eta>
    </animale>

    <animale>
        <nome>Gigia</nome>
        <sesso>Female</sesso>
        <eta>2</eta>
    </animale>
</area>

<area id="2" posizione="nord" nome="giraffe">
    <animale>
        <nome>Giro</nome>
        <sesso>Male</sesso>
        <eta>6</eta>
    </animale>

    <animale>
        <nome>Gira</nome>
        <sesso>Female</sesso>
        <eta>5</eta>
    </animale>
</area>
</zoo>

码:

my $parser = XML::LibXML->new;
my $doc = $parser->parse_file("../xml/animals.xml");
my $root = $doc->getDocumentElement();

my $new_animal = $doc->createElement("animale");

my $name_element = $doc->createElement("nome");
$name_element->appendTextNode($name);

my $gender_element = $doc->createElement("sesso");
$gender_element->appendTextNode($gender);

my $age_element = $doc->createElement("eta");
$age_element->appendTextNode($age);

$new_animal->appendChild($name_element);
$new_animal->appendChild($gender_element);
$new_animal->appendChild($age_element);

my $area_element = $root -> findnodes("//area[@id=$area]")->get_node(1);

$area_element->appendChild($new_animal);

$area是一个区域的id(现在通常是我测试的1)

我的目的是创造一种新的动物并将其添加到适当的区域

但我有问题,即建筑

my $area_element = $root -> findnodes("//area[@id=$area]")->get_node(1);

不起作用,因为$area_element是undef,因为findnodes总是返回一个空的节点列表(选中打印size()).

我认为问题是findnodes中的xpath表达式,但是我无法理解什么是错的,我使用与另一个库(XML :: XPath)相同的表达式并且它正在工作.

怎么了?

解决方法

XML中的deafult命名空间的URI是http://www.zoo.com,因此您必须在XPath表达式中指定要获取的节点.

执行此操作的方法是声明一个XML :: LibXML :: XPathContext对象,该对象为此命名空间指定名称.然后可以在XPath表达式中使用该名称来访问节点.

如果你写

my $xpc = XML::LibXML::XPathContext->new;
$xpc->registerNs('zoo','http://www.zoo.com');

您现在有一个上下文,其中XML的默认命名空间名为zoo.现在你可以写了

my $area_element = $xpc->findnodes("//zoo:area[@id=$area]",$doc)->get_node(1);

你会发现正确的< area>元件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读