Writing updates to xml file with XQuery and BaseX

1.2k views Asked by At

I have a file.xml storing protocols whose structure is the following:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<economato> 
  <protocollo>
    <numero>1</numero>
    <data>2014-12-15</data>
    <oggetto>Trasmissione prospetti di rendiconto chiusura esercizio 2012 - beni mobili proprietà dello stato</oggetto>
    <destinatario>Ragioneria Provinciale Como</destinatario>
    <operatore>MAESTRI</operatore>
    <valido>true</valido>
  </protocollo>
  ...
</economato>

and I would need to change/update the value of the tag "valido", for example from 'true' to 'false' of the protocollo number 1 and I would like this update to be written into the file. As I am using BaseX, following the documentation I have tried to write this query:

xquery let $update := doc('C:\Users\Lorenzo Enzino  Vinci\Desktop\ECONOMATO\databases\2014.xml')//economato/protocollo[numero = 1] return replace value of node $update/valido with 'false' into doc('C:\Users\Lorenzo Enzino Vinci\Desktop\ECONOMATO\databases\2014.xml')//economato

but I get an error like

[XPST0003] Unexpected end of query: 'into doc('C:\Users\Lorenzo Enzino Vinci\Desktop\ECONOMATO\databases\2014.xml')//economato'

So my query is wrong but I do not know where. Can you help me?

1

There are 1 answers

2
dirkk On BEST ANSWER

It fails, because it is invalid XQuery Update syntax. There is not replace ... with ... into ... command, there only is replace ... with ..., as the error message already indicates. It would also be unlogical, because $update already holds a reference to the correct xml fragment.

So you simply have to use the following XQuery:

let $update := doc('C:\Users\Lorenzo Enzino  Vinci\Desktop\ECONOMATO\databases\2014.xml')//economato/protocollo[numero = 1]
return replace value of node $update/valido with 'false'

Also, please note that updates are not automatically written back to files in the file system (to avoid accidentally overwriting files), e.g. by starting it with basex -u. This is explained in detail in the BaseX wiki