in reply to xmlns and XML::LibXML

Have a look at XML::LibXML::XPathContext (e.g. "Namespaces" in "Examples").

Replies are listed 'Best First'.
Re^2: xmlns and XML::LibXML
by worik (Sexton) on Jun 02, 2015 at 03:28 UTC

    I cannot see how to use. XML::LibXML::XPathContext

    The man page says:

    registerNs $xpc->registerNs($prefix, $namespace_uri) Registers namespace $prefix to $namespace_uri.

    But I do not know in advance what the prefix will be.

    <?xml version="1.0" encoding="utf-8" ?> <propfind xmlns="DAV:"> <propname/> </propfind>

    Is valid and

    <?xml version="1.0" encoding="utf-8" ?> <D:propfind xmlns:D="DAV:"> <D:prop xmlns:R="http://ns.example.com/boxschema/"> <R:bigbox/> <R:author/> <R:DingALing/> <R:Random/> </D:prop> </D:propfind>

    is valid too.

    Worik

      But I do not know in advance what the prefix will be.

      You don't need to know it, a prefix is for your xpaths, the namespace is important not the prefix, the prefix is just a shortcut for the namespace

      The person writing xml "registers" a local prefix so they can write their XML with less chars

      The person writing xpath "registers" a local prefix so they can write their xpath with less chars

      Neither person has to use the same prefix to refer to the same namespace

      The prefix used in the XPath doesn't have to match the prefix used in the document. Only the namespaces need to match. Pick a prefix of your liking. See Re^2: xmlns and XML::LibXML.
      I cannot see how to use. XML::LibXML::XPathContext

      Please read the replies carefully. A working piece of example code was given to you an hour before you posted this.

Re^2: xmlns and XML::LibXML
by Anonymous Monk on Jun 02, 2015 at 02:38 UTC

    The key is that the prefixes used in the XPath expression don't have to have anything to do with the prefixes in the XML file. The following works fine on both your example XML inputs.

    my $xml = XML::LibXML->load_xml(string => $txt1); my $xc = XML::LibXML::XPathContext->new($xml); $xc->registerNs('foo', 'DAV:'); print "prop:\n"; print "$_\n" for $xc->findnodes('/foo:propfind/foo:prop'); print "propname:\n"; print "$_\n" for $xc->findnodes('/foo:propfind/foo:propname');