Why should I use XPathContext with Perl's XML::LibXML?

后端 未结 1 672
清酒与你
清酒与你 2021-01-06 13:36

This script works with and without XPathContext. Why should I use it with XPathContext?

#!/usr/bin/env perl
use warnings; use stric         


        
相关标签:
1条回答
  • 2021-01-06 13:49

    The primary reason for using XPathContext elements is namespaces. Your document has no namespaces so XPathContexts don't add anything to your query. Now, imagine that you actually had the following xml

    my $doc = $parser->parse_string(<<EOT);
    <?xml version="1.0"?>
    <xml xmlns="http://my.company.com/ns/nsone" 
        xmlns:ns2="http://your.company.com/nstwo">
        Text im Dokument
        <ns2:element id="myID" name="myname" style="old" />
        <object objid="001" objname="Object1" />
        <element id="002" name="myname" />
    </xml>
    EOT 
    

    You would need to define an XPathContext in order to have namespaces defined so that you could make namespace aware XPath queries:

    my $root = $doc->documentElement;
    my $xc = XML::LibXML::XPathContext->new( $root );
    $xc->registerNs("ns2", "http://your.company.com/nstwo");
    $xc->registerNs("ns1", "http://my.company.com/nsone");
    my $nodes = $xc->findnodes( '/ns1:xml/ns2:element[@id="myID"]' );
    

    Otherwise, you have no simple way to use namespace aware XPath statements.

    0 讨论(0)
提交回复
热议问题