David Slavík
David Slavík

Reputation: 1192

How to compare two xml objects with xslt?

I want to compare two XML nodes in one XML file, compare were are differences and write summary.

Here is my xml data:

<AuditLog>
   <OldValue>
      <ProcessCategory>
         <CategoryId>3</CategoryId>
         <ChildCategories />
         <Created>2012-12-13T11:39:30.747</Created>
         <Name>New category name</Name>
         <ParentCategory />
      </ProcessCategory>
   </OldValue>
   <NewValue>
     <ProcessCategory>
        <CategoryId>3</CategoryId>
        <ChildCategories />
        <Created>2012-12-13T11:39:30.747</Created>
        <Name>Old Category name</Name>
        <ParentCategory />
     </ProcessCategory>
   </NewValue>
</AuditLog>

I need result like:

Difference in property category Name, old value: "Old Category name", new value: "New category name"

Can anyone help me, please?

Upvotes: 0

Views: 1002

Answers (2)

Jan Nov&#225;k
Jan Nov&#225;k

Reputation: 594

You can iterate thru all properties and compare their values. If object's structure is not more nested then in your example, this should work:

    <xsl:template match="/">
      <xsl:for-each select="AuditLog">

        <xsl:call-template name="for">
          <xsl:with-param name="i">0</xsl:with-param>
          <xsl:with-param name="max" select="count(OldValue/*/*)" />
        </xsl:call-template>

      </xsl:for-each>
    </xsl:template>

  <xsl:template name="for">
    <xsl:param name="i" />
    <xsl:param name="max" />

    <xsl:variable name="oldValue" select="OldValue/*/*[$i]" />    
    <xsl:variable name="newValue" select="NewValue/*/*[$i]" />
    <xsl:variable name="prop" select="name(OldValue/*/*[$i])" />

    <xsl:if test="not($newValue=$oldValue)">
      <Changed Property="{$prop}" oldValue="{$oldValue}" newValue="{$newValue}" />
    </xsl:if>

    <xsl:if test="$i &lt; $max">
      <xsl:call-template name="for">
        <xsl:with-param name="i" select="$i+1" />
        <xsl:with-param name="max" select="$max" />
      </xsl:call-template>
    </xsl:if>

  </xsl:template>                

Upvotes: 2

Patrik Melander
Patrik Melander

Reputation: 585

It's been while since i wrote XSLT so the XPATH might be off, but try this:

<xsl:if test="not(OldValue/ProcessCategory/Name=NewValue/ProcessCategory/Name">
    Old Name: <xsl:value-of select="OldValue/ProcessCategory/Name"/>
    New Name: <xsl:value-of select="NewValue/ProcessCategory/Name"/>
</xsl:if>

Upvotes: 0

Related Questions