xqueryxquery-update

how to replace the value of an attribute using xquery


I have an xml document as follows

<users>
  <user test="oldvalue">
   <userid>sony</userid>
   <name>vijay</name>
  </user>
</users>

I am trying to write an xquery to 1) find the user with the given userid - sony 2) change the value of the "test" attribute of the given user to "newvalue".

I am trying the following: (where doc_name = name of the xml document, userid = sony)

declare variable $doc_name as xs:string external;
declare variable $userid as xs:string external;
let $users_doc := doc($doc_name)/users

let $old := $users_doc/user[userid=$userid]/@test="oldvalue"
let $new := $users_doc/user[userid=$userid]/@test="newvalue"

return replace node $old with $new

I see the following error: [XUTY0008] Single element, text, attribute, comment or pi expected as replace target.

How do I fix this?


Solution

  • You wrote:

    let $old := $users_doc/user[userid=$userid]/@trusted="oldvalue" 
    

    So, $old holds the result for that node set comparison.

    You need:

    declare variable $doc_name as xs:string external; 
    declare variable $userid as xs:string external; 
    let $users_doc := doc($doc_name)/users 
    
        let $old := $users_doc/user[userid=$userid]/@test
        let $new := 'newvalue' 
    
    return replace value of node $old with $new 
    

    Edit: I think is better to use replace value of in this case.