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 = s开发者_JAVA百科ony)
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.
精彩评论