如何使用XSLT比较基于属性值的2个XML文件以查找公共节点?

时间:2020-06-25 18:09:48

标签: xml xslt

我有两个XML:-

file1.xml

<ConnectorConfig>
<service uri="/gen5">
<routeUrl>http://localhost:3003/v5</routeUrl>
</service>
<service uri="/gen6">
<routeUrl>http://localhost:3003/v6</routeUrl>
</service>
<service uri="/gen7">
<routeUrl>http://localhost:3003/v7</routeUrl>
</service>
</ConnectorConfig>

file2.xml

<ConnectorConfig>
<service uri="/gen5">
<routeUrl>http://localhost:3003/v51</routeUrl>
</service>
<service uri="/gen6">
<routeUrl>http://localhost:3003/v61</routeUrl>
</service>
<service uri="/gen9">
<routeUrl>http://localhost:3003/v91</routeUrl>
</service>
<service uri="/gen8">
<routeUrl>http://localhost:3003/v81</routeUrl>
</service>
</ConnectorConfig>

所需的期望输出是:

<ConnectorConfig>
<service uri="/gen5">
<routeUrl>http://localhost:3003/v51</routeUrl>
</service>
<service uri="/gen6">
<routeUrl>http://localhost:3003/v61</routeUrl>
</service>
</ConnectorConfig>

这是我为生成所需结果而尝试的:

 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="ConnectorConfig">
      
     <xsl:variable name="item" select="document('file2.xml')/ConnectorConfig/service[@uri = current()/service/@uri]/*"/> 

    <xsl:if test="$item">     
     <xsl:copy>
      <xsl:apply-templates select="@*|$item"/>
     </xsl:copy>
    </xsl:if>  

  </xsl:template>
</xsl:stylesheet>

这是我到目前为止尝试过的..但没有运气。

Output.xml

<ConnectorConfig>
    <routeUrl>http://localhost:3003/v51</routeUrl>
    <routeUrl>http://localhost:3003/v61</routeUrl>
</ConnectorConfig>

在以上响应中,仅需要服务标签即可实现我所需的输出。
我在做什么错? 请帮忙。

1 个答案:

答案 0 :(得分:1)

您正在选择匹配的service元素的子元素。

您要选择service元素。

/*的{​​{1}}变量中删除@select

$item
相关问题