【问题标题】:To match the attribute value from two different xml and replace the text using XSLT匹配来自两个不同 xml 的属性值并使用 XSLT 替换文本
【发布时间】:2018-03-26 11:02:00
【问题描述】:

匹配两个不同xml文件的属性值并替换文本 1.xml

<?xml version="1.0" encoding="UTF-8"?>
<hostids>
   <hostid id="001">Agent</hostid>
   <hostid id="002">test2</hostid>
</hostids>

2。 xml

<?xml version="1.0" encoding="UTF-8"?>
<resources>
   <resource>
      <host id="001">jaffar 123</host>
   </resource>
   <resource>
      <host id="002">school 234</host>
   </resource>
</resources>

输出:我需要

<hostids>
   <hostid id="001">jaffar 123</hostid>
   <hostid id="002">school 234</hostid>
</hostids>

【问题讨论】:

    标签: xslt-1.0 xslt-2.0


    【解决方案1】:

    定义一个键&lt;xsl:key name="ref" match="resource/host" use="@id"/&gt;,然后编写一个模板检查是否存在交叉引用并替换内容,在XSLT 3中可以使用

    <xsl:template match="hostid[key('ref', @id, $doc2)]/text()">{key('ref', ../@id, $doc2)}</xsl:template>
    

    在 XSLT 2 中你需要

    <xsl:template match="hostid[key('ref', @id, $doc2)]/text()">
      <xsl:value-of select="key('ref', ../@id, $doc2)"/>
    </xsl:template>
    

    https://xsltfiddle.liberty-development.net/6qM2e2r 上的 XSLT 3 示例在线

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        expand-text="yes"
        version="3.0">
    
      <xsl:mode on-no-match="shallow-copy"/>
    
      <xsl:param name="doc2">
        <resources>
           <resource>
              <host id="001">jaffar 123</host>
           </resource>
           <resource>
              <host id="002">school 234</host>
           </resource>
        </resources>
      </xsl:param>
    
      <xsl:key name="ref" match="resource/host" use="@id"/>
    
      <xsl:template match="hostid[key('ref', @id, $doc2)]/text()">{key('ref', ../@id, $doc2)}</xsl:template>
    
    </xsl:stylesheet>
    

    显然您可以使用&lt;xsl:param name="doc2" select="doc('file2.xml')"/&gt; 从另一个文件中读取第二个文档。

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 1970-01-01
      • 2022-01-21
      • 2012-08-03
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-04
      相关资源
      最近更新 更多