【问题标题】:How to compare 2 XML files based on attribute values using XSLT to find common nodes?如何使用 XSLT 根据属性值比较 2 个 XML 文件以查找公共节点?
【发布时间】:2020-06-25 18:09:48
【问题描述】:

我有两个 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>

这是我迄今为止尝试过的......但没有运气。

输出.xml

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

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

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

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

    您要选择service 元素。

    @select 中为您的$item 变量删除/*

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

    【讨论】:

    • 非常感谢您的帮助。谢谢。
    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 2021-02-04
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多