简体   繁体   中英

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?

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.

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

The type of $old is xs:boolean -- not a node type. Therefore, the error message you get is correct.

You want :

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

BTW: There is no replace operator in the standard XQuery .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM