Insert update attribute

apb2006
2009-06-01
2013-06-05
  • apb2006
    apb2006
    2009-06-01

    I am trying to use mxquery 0.6 to update an attribute or insert it if not there.

    My db.xml file is like this
    -----------
    <?xml version='1.0' encoding='UTF-8' ?>
    <db>
       <rec key="1">Apple</rec>
       <rec key="2" timestamp="2009-06-01T15:34:27.857Z">BB</rec>
       <rec key="3">orange</rec>
       <rec key="4" fred="2009-06-01T15:34:27.857Z">DD</rec>
    </db>
    -----------
    My Xquery is
    ------------------
    (: xquery update test: update or insert timestamps  :)
    declare updating function
       local:upsert($e as element(),
              $an as xs:QName,
              $av as xs:anyAtomicType)
       {
       let $ea := $e/attribute()[fn:node-name(.) = $an]
       return
       
          if (fn:empty($ea))
          then insert node attribute {$an} {$av} into $e
          else replace value of node $ea with $av
        
       };

    let $db:=doc("db.xml")

    for $r in $db//rec
    return  local:upsert($r,timestamp,current-time())
    -----------------------

    I am getting a Context item not set error. Is this due to my lack of understanding or is it a mxquery issue?

    /Andy

     
    • apb2006
      apb2006
      2009-06-02

      I think I have got it, using QName works :-)

      local:upsert($r,QName("","timestamp"),current-time())

       
    • Maybe a little bit of clarification:

      local:upsert($r,timestamp,current-time()) is actually

      local:upsert($r,./timestamp,current-time()),

      since timestamp is a child location step instead of string.

      In the absence of Schema information, it cannot be determined statically that this location step will not produce a QName (or something that can be cast into a QName)

      Hope that helps,

      Peter

       
    • apb2006
      apb2006
      2009-06-02

      Thanks, I spent a long time going round in circles with this. I expected this to work...

      upsertAttribute($r,"timestamp",current-time())

      but it produces a "Type not allowed" error - no doubt correctly, so I removed the quotes in desperation.

      After I sent the message I realised that this was an xpath with no "context".

      Are you saying the .."timestamp".. form could be made to work in the presense of suitable Schema information?  

      Andy

       
    • No, the timestamp (path expression) case could be analyzed better with schema knowledge and static typing to show that there will be an error.

      Just a quick hint: I don't know which editor you are using to write XQuery. The problem of using a path expression instead of a string/QName is solved nicely in XQDT, which is open source XQuery plugin for Eclipse.

      Peter