Tuesday 26 July 2011

XQuery - finding changes in the trees

Given a set of node names I wanted to compare the data/text of these nodes from two structurally identical documents. This follows on from a previous post where we needed to translate the character sets for a given node's data/text; by comparing the before and after trees we can log what was actually changed before it was sent onto the next system.

The following XQuery takes a sequence of node names (as before), as well as the original and new documents; by comparing the relevant element's data it returns a string containing old and new values where they differ. This string is mainly useful for logging purposes.

declare namespace tmp = "http://www.tempuri.co.nz/xquery/";

declare function tmp:stringChangeList($nodeNames as xs:string*,$oldOutput as element(),$newOutput as element()) as xs:string* {
 for $curNodeName in $nodeNames
 let $oldValues := $oldOutput//*[name() = $curNodeName]
 for $oldValuePosition in (1 to count($oldValues))
 let $oldValueNode := $oldValues[$oldValuePosition]
 let $newValueNodeList := $newOutput//*[name() = $curNodeName]
 let $newValueNode := $newValueNodeList[$oldValuePosition]
 where data($oldValueNode) != data($newValueNode)
 return concat("(",$curNodeName," - Old: ",data($oldValueNode),", New: ",data($newValueNode),")")
};

No comments:

Post a Comment