XQuery/Compare two XML files

From Wikibooks, open books for an open world
Jump to: navigation, search

Motivation[edit]

You want to compare two XML files. If the files are the same you want to return a true and if not you want to return a false. Note if you want to see the differences see the XQuery/XML Differences example.

Method[edit]

We will use the xdiff:compare() function that comes built in to eXist. To use this you pass two nodes to the compare function:

xdiff:compare($node1 as node(), $node2 as node())

Sample Source Code[edit]

Assume you have two different XML files

xquery version "1.0";
import module namespace xdiff="http://exist-db.org/xquery/xmldiff"  at "java:org.exist.xquery.modules.xmldiff.XmlDiffModule"; 
 
let $doc1 := '/db/apps/xml-diffs/data/diff1.xml'
let $doc2 := '/db/apps/xml-diffs/data/diff2.xml'
 
return
<results>
   <result>diff of 1,1: {xdiff:compare(doc($doc1), doc($doc1))}</result>
   <result>diff of 1,2: {xdiff:compare(doc($doc1), doc($doc2))}</result>
   <result>diff of 2,2: {xdiff:compare(doc($doc2), doc($doc2))}</result>
</results>

The result will be:

<results>
   <result>diff of 1,1: true</result>
   <result>diff of 1,2: false</result>
   <result>diff of 2,2: true</result>
</results>