XPath Searches In Vim

Ovid on 2008-06-13T14:11:46

I've just started on this, but I'm getting tired of working with XML documents in vim and having trouble finding what I want. After all, vim's usual regexes don't work terribly well with XML. So I have this program that I have cleverly named "xpath":

#!/usr/bin/env perl

use strict;
use warnings;

use XML::XPath;
use XML::XPath::XMLParser;

my ( $filename, $xpath ) = @ARGV;

my $xp = XML::XPath->new(filename => $filename );

my $nodeset = $xp->find($xpath);    # find all paragraphs

my $found = 0;
foreach my $node ($nodeset->get_nodelist) {
    $found++;
    print "FOUND\n\n", XML::XPath::XMLParser::as_string($node), "\n\n";
}

unless ($found) {
    print "No XML found matching xpath '$xpath'\n";
}

And in my .vimrc

|au! FileType xml           :call XMLMappings()

function! XMLMappings()
    noremap xf :%!xmllint --format %
    noremap xp :call Xpath()
endfunction

function! Xpath()
    let filename = bufname("%")
    let xpath    = input("Enter xpath expression: ")
    let command  = "xpath '" . filename . "' '" . xpath . "'"
    echo system(command)
endfunction

Now I just type ',xp' in an XML document, it prompts me for the xpath and shows me all nodes in the document matching said xpath.

I need to do some more work to figure out line numbers, if possible.


XML::XPath?

grantm on 2008-06-14T01:20:49

Any particular reason why you're using XML::XPath rather than XML::LibXML?

Re:XML::XPath?

Ovid on 2008-06-14T08:10:02

Because we managed to screw up tons of XML a long time ago and have not yet properly handled the namespaces. One that's done we'll make the switch.

Re:XML::XPath?

Richard Rathmann on 2008-06-15T14:23:27

Well, once you switch to XML::LibXML, it can solve your issue with figuring out line numbers.