Search code examples
xmlxqueryexist-db

insert into database - xquery and exist db


I just started using eXist and tried to insert data into an xml file. So far, I did this in .xql file:

declare function app:save($node as node(), $model as map(*), $name as xs
:string?, $author as xs :string?, $isbn as xs :integer?, $date as xs :integer?) {
for $books in doc("/db/apps/tutorial/library.xml")//LIBRARY/books
  return 
  update insert 
  <name>$name</name>
  <author>$author</author>
  <isbn>$isbn</isbn>
  <date>$date</date>
  into $books
};

and the hierarchy in my xml file file simply looks like this:

<?xml version="1.0"?>
<LIBRARY>
    <books>
    </books>
    <magazines>
    </magazines>
    <audio>
    </audio>
    <video>
    </video>
</LIBRARY>

I simply need to insert the metadata(which comes from html) about a book but exide gives me "unexpected token: >". It might be a simple question but I got stuck. Your contribution will be highly appreciated.


Solution

  • Update statements expect a single node or a sequence of nodes.

    Either you forgot a wrapping node like <book/>, resulting in something like

    update insert <book>
      <name>{ $name }</name>
      <author>{ $author }</author>
      <isbn>{ $isbn }</isbn>
      <date>{ $date }</date>
    </book>
    into $books
    

    or you have to pass a sequence, with the individual elements seperated by colons:

    update insert (
      <name>{ $name }</name>,
      <author>{ $author }</author>,
      <isbn>{ $isbn }</isbn>,
      <date>{ $date }</date>
    ) into $books
    

    Additionally, you will probably have to declare the function as updating (as discussed in the comments, not for eXist DB):

    declare updating function app:save(...) { ... }