如何比较两个xml对象与xslt?

时间:2012-12-17 08:46:55

标签: xml xslt

我想比较一个XML文件中的两个XML节点,比较差异和写入摘要。

这是我的xml数据:

<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>

我需要结果如:

属性类别的区别名称,旧值:“旧类别名称”,新值:“新类别名称”

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

您可以遍历所有属性并比较它们的值。如果对象的结构没有嵌套,那么在您的示例中,这应该有效:

    <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>                

答案 1 :(得分:0)

我写XSLT已经有一段时间了,所以XPATH可能会关闭,但试试这个:

<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>
相关问题