[xquery-talk] adding or modifing an attribute

Michael Kay mike at saxonica.com
Fri Jun 6 09:46:35 PDT 2008


In the absence of XQuery Updates, this kind of problem is rather tedious to
solve in XQuery, at least in comparison with the XSLT solution. 

You basically need to write a recursive function that is called to process
each node in the tree, and that calls itself to process its children.
Something like this:

declare function local:copy-and-change($nodes as node()*) as node()* {
for $in in $nodes return
  typeswitch ($in) {
  case element(name):
    <name> {
         @* except @average,
         attribute average {90},
         local:copy-and-change(child::node())
    } </name>
  case element():
    element {node-name($in)} {
         @*,
         local:copy-and-change(child::node())   
    }
  default:
    $in
}

local:copy-and-change(/*)

Note that this code will drop any namespaces that aren't used in element and
attribute names - don't use it if your document has namespace-sensitive
content such as xsi:type attributes. (I don't know of any general answer to
that problem.)

Michael Kay
http://www.saxonica.com/

> -----Original Message-----
> From: talk-bounces at x-query.com 
> [mailto:talk-bounces at x-query.com] On Behalf Of Sam Carleton
> Sent: 04 June 2008 17:03
> To: talk at x-query.com
> Subject: [xquery-talk] adding or modifing an attribute
> 
> I have worked with DOM, SAX, XSLT, and XPath in the past and 
> am now working with a framework that has XQuery.  The task at 
> hand is very simple, change (or add if not present) an 
> attribute to one element in an XML document:
> 
> Example: If the name element has an average attribute, change 
> it to 93, otherwise create it and set it to 93
> input:
> 
> <root>
>  <students>
>    <name value="scott"/>
>  </students>
> </root>
> 
> or
> 
> <root>
>  <students>
>    <name value="scott" average="90"/>
>  </students>
> </root>
> 
> output:
> 
> <root>
>  <students>
>    <name value="scott" average="93"/>
>  </students>
> </root>
> 
> How might I do this with XQuery?  The framework I am using is 
> Trolltech's Qt which is a C++ framework.  I am under the 
> impression I am going to have to load the XML document into 
> memory, execute the XQuery query on it that will result in a 
> new XML document that I will then save over the original XML 
> file, is that correct?  I can figure out the Qt stuff, the 
> real question is how would I put together a query to make 
> this change in XQuery?
> 
> Sam
> _______________________________________________
> talk at x-query.com
> http://x-query.com/mailman/listinfo/talk



More information about the talk mailing list