示例 XML 文档
<?xml version="1.0" encoding="UTF-8"?>
<web-interface-classifier xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="WEB-INTERFACE-GROUP-CLASSIFIER.xsd" xmlns="parent/child1/granchild2/v1">
<classifier>
<key1>somevalue</key1>
</classifier>
<classifier>
<key2>somevalue</key2>
</classifier>
</web-interface-classifier>
用于解析上述 XML 文档的代码。
my $dom = XML::LibXML->load_xml(location => $filename);
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs( xsi => "http://www.w3.org/2001/XMLSchema-instance" );
foreach my $node ($xpc->findnodes("web-interface-classifier/classifier", $dom)) {
print Dumper($node);
}
我尝试解析XML文档并从"分类器"节点转储所需的键值对,但未检测到所需的子节点。你能提供一些指示吗?
您正在尝试从 parent/child1/granchild2/v1
命名空间中查找类型 web-interface-classifier
和 classifier
的元素,但您要求从 null 命名空间中查找类型为 web-interface-classifier
和 classifier
的元素。固定:
#!/usr/bin/env perl
use strict;
use warnings;
use v5.10;
use Data::Dumper;
use XML::LibXML;
use XML::LibXML::XPathContext;
my $dom = XML::LibXML->load_xml( IO => *DATA );
my $xpc = XML::LibXML::XPathContext->new();
$xpc->registerNs( u => "parent/child1/granchild2/v1" );
for my $node ( $xpc->findnodes( "//u:web-interface-classifier/u:classifier", $dom ) ) {
say $node->toString();
}
__DATA__
<?xml version="1.0" encoding="UTF-8"?>
<web-interface-classifier xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:noNamespaceSchemaLocation="WEB-INTERFACE-GROUP-CLASSIFIER.xsd" xmlns="parent/child1/granchild2/v1">
<classifier>
<key1>somevalue</key1>
</classifier>
<classifier>
<key2>somevalue</key2>
</classifier>
</web-interface-classifier>
输出:
<classifier>
<key1>somevalue</key1>
</classifier>
<classifier>
<key2>somevalue</key2>
</classifier>