0

我对 XML 完全陌生,所以我不知道该怎么做:

假设我有以下 XML 文件 1 :

<Items>
<Item>
   <name> Item1 </name>
   <value> 10   </value>
</Item>
</Items>

和文件 2:

<Items>
    <Item>
       <name> Item1 </name>
       <value> 20   </value>
    </Item>
    </Items>

如何使用 XSLT 以任何方式比较这两项的值字段?

4

1 回答 1

1

您可以将如下所示的样式表应用于您的第一个 XML,并将第二个 XML 文档的路径作为 a 传递param(阅读 XSLT 处理器的文档以了解如何传递参数)。

模板将检查 XML #1 中的每一项,在另一个 XML ( ) 中<Item>找到相同的第一项并比较它们各自的 s。<name>$otherDoc//Item[name = $ownName][1]/value<value>

然后它会生成文本输出,每进行一次这样的比较就一行。

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" />

  <xsl:param name="otherDocPath" select="''" />

  <xsl:variable name="otherDoc" select="document($otherDocPath)" />

  <xsl:template match="/">
    <!-- handle each item in this document -->
    <xsl:apply-templates select="/Items/Item" />
  </xsl:template>

  <xsl:template match="Item">
    <xsl:variable name="ownName" select="name" />
    <xsl:variable name="ownValue" select="value" />
    <xsl:variable name="otherValue" select="$otherDoc//Item[name = $ownName][1]/value" />

    <!-- output one line of information per item -->
    <xsl:value-of select="concat($ownName, ': ')" />

    <xsl:choose>
      <xsl:when test="$ownValue = $otherValue">
        <xsl:value-of select="concat('same value (', $ownValue, ')')" />
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="concat('different (', $ownValue, '/', $otherValue, ')')" />
      </xsl:otherwise>
    </xsl:choose>

    <xsl:text>&#xA;</xsl:text><!-- new line -->
  </xsl:template>

</xsl:stylesheet>

注意名称/值周围的空格。如果您的输入真的看起来像<value> 10 </value>,您想normalize-space()在比较/输出任何东西(<xsl:variable name="ownValue" select="normalize-space(value)" />等)之前使用。

输出看起来像:

第 1 项:不同 (10/20)
项目2:相同的值(20)
第 3 项:不同 (20/)

其中第 1 行和第 2 行代表两个 XML 文档中的项目,第 3 行代表仅在第一个文档中的项目。

当然文本输出只是一种可能,您可以输出不同的格式(XML、HTML)。

于 2013-03-20T08:33:02.060 回答