我有两个XML
File1.xml它包含需要多次复制的IP的映射,并用给定的值替换值。
<baseNode>
<internal ip="192.168.1.1">
<someOtherTags>withsome values which should not be changed</someOtherTags>
</internal>
<internal ip="192.168.1.2">
<someOtherTags>withsome more values which should not be changed</someOtherTags>
</internal>
</baseNode>
File2.xml
<IPMappings>
<sourceIP value="192.168.1.1">
<replacement>10.66.33.22</replacement>
<replacement>10.66.33.44</replacement>
</sourceIP>
<sourceIP value="192.168.1.2">
<replacement>10.66.34.22</replacement>
<replacement>10.66.34.44</replacement>
</sourceIP>
</IPMappings>
生成的XML应该是:
<baseNode>
<internal ip="10.66.33.22">
<someOtherTags>withsome values which should not be changed</someOtherTags>
</internal>
<internal ip="10.66.33.44">
<someOtherTags>withsome values which should not be changed</someOtherTags>
</internal>
<internal ip="10.66.34.22">
<someOtherTags>withsome more values which should not be changed</someOtherTags>
</internal>
<internal ip="10.66.34.44">
<someOtherTags>withsome more values which should not be changed</someOtherTags>
</internal>
</baseNode>
如何使用XSLT执行此操作?
答案 0 :(得分:1)
这是我的建议,第一个文档是主要输入文档,第二个文档作为参数传入:
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:param name="map-doc-url" select="'File2.xml'"/>
<xsl:variable name="map-doc" select="document($map-doc-url)"/>
<xsl:output indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="ip" match="sourceIP" use="@value"/>
<xsl:template match="baseNode">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="baseNode/internal">
<xsl:variable name="this" select="."/>
<xsl:for-each select="$map-doc">
<xsl:apply-templates select="key('ip', $this/@ip)/replacement">
<xsl:with-param name="internal" select="$this"/>
</xsl:apply-templates>
</xsl:for-each>
</xsl:template>
<xsl:template match="sourceIP/replacement">
<xsl:param name="internal"/>
<internal ip="{.}">
<xsl:copy-of select="$internal/node()"/>
</internal>
</xsl:template>
</xsl:stylesheet>
当我使用Saxon 6.5.5运行时,我得到以下结果:
<baseNode>
<internal ip="10.66.33.22">
<someOtherTags>withsome values which should not be changed</someOtherTags>
</internal>
<internal ip="10.66.33.44">
<someOtherTags>withsome values which should not be changed</someOtherTags>
</internal>
<internal ip="10.66.34.22">
<someOtherTags>withsome more values which should not be changed</someOtherTags>
</internal>
<internal ip="10.66.34.44">
<someOtherTags>withsome more values which should not be changed</someOtherTags>
</internal>
</baseNode>