Marta Karas
Marta Karas

Reputation: 5165

vim how to insert line with the values extracted from the xml file

I have an xml file in which I expect to find some particular tags with values that I want to use to build an url. I would like to:

  1. find these values
  2. make an url with them
  3. insert this url at the beginning of a file

For example, given xml file starting with:

<?xml version="1.0" encoding="utf-8"?>
<file_1_doc>
    <biul>1</biul>
    <poz>33792</poz>          
    <date_pub>2015-02-16</date_pub>

(...)

I want to produce an url in the base form:

http://foo.com/index.php?biul=show&position=[poz]&publdate=[date_pub]

having for the example above:

http://foo.com/index.php?biul=show&position=33792&publdate=2015-02-16

Upvotes: 0

Views: 51

Answers (1)

Ingo Karkat
Ingo Karkat

Reputation: 172648

  1. find these values

You need an XML parser; Vim cannot do this properly (unless the XML is always consistently structured and doesn't use specials like XML named entities, where you may attempt to parse using regular expression (matchstr()), but read this first).

Vim can embed various scripting languages, e.g. Python (:help if_pyth.txt). With their default libraries, XML parsing shouldn't be a big problem. Else, you can invoke an external tool (e.g. xmlstar) via system().

  1. make an url with them

Once you've got the parsed XML in Vim variable(s), this can be comfortably done via printf().

  1. insert this url at the beginning of a file

Again, various easy ways. For a completely new line, :call append(); to add to a line, either :execute 'normal! a' . text or the lower-level call setline(, getline(1) . ...).

Upvotes: 4

Related Questions