Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Ovid (2709)

Ovid
  (email not shown publicly)
http://publius-ovidius.livejournal.com/
AOL IM: ovidperl (Add Buddy, Send Message)

Stuff with the Perl Foundation. A couple of patches in the Perl core. A few CPAN modules. That about sums it up.

Journal of Ovid (2709)

Friday June 13, 2008
09:11 AM

XPath Searches In Vim

[ #36682 ]

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 <leader>xf :%!xmllint --format %<cr>
    noremap <leader>xp :call Xpath()<cr>
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.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.