没有在perl中解析名称空间的xml

时间:2017-11-11 10:53:28

标签: xml perl libxml2 xml-libxml

我有一个带有默认命名空间的xml,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<start xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:schemaLocation="http://127.0.0.1 GrammarXSD.xsd" version="01.00" xmlns="GrammarXSD.xsd">
    <DataModel>
        #rest of the xml
    </DataModel>
</start>

要解析此xml,我尝试使用以下代码注册命名空间:

my $file = "xml file location";
my $dom = XML::LibXML->load_xml(location => $file);
my $xpc = XML::LibXML::XPathContext->new($dom->documentElement());
$xpc->registerNs('ns',  'GrammarXSD.xsd');
my $b = $dom->findnodes('//ns:DataModel');

但是,这并没有按预期找到DataModel节点。 GrammarXSD.xsd文件与xml位于同一位置。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:4)

您必须使用XPathContext对象以名称空间感知方式搜索节点:

my $data_models = $xpc->findnodes('//ns:DataModel', $dom);

BTW,不要使用my $b,$ b是sort中使用的特殊变量,如果稍后在同一范围内使用sort,则将其声明为词汇会导致错误。

此外,命名空间URI并不意味着什么,它只是标识命名空间。