2012-12-17 10 views
0

我想比较一个XML文件中的两个XML节点,比较是差异和写总结。如何使用xslt比较两个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

可以遍历直通所有属性,并比较它们的值。如果对象的结构不是多个嵌套那么在你的榜样,这应该工作:

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

很好的解决方案Jan –

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

还检查了这个帖子:http://stackoverflow.com/questions/5649241/to-compare-two-elementsstring-type- in-xslt –

+0

您是否可以编辑抽象的XML源代码的解决方案?我只知道结构AuditLog/OldValue,AuditLog/NewValue,并且不知道具体的属性名称......另外,您的解决方案对我来说非常费力:( –