XSLT用于XML元素中的replace属性(如果它存在于另一个XML中)? [英] XSLT for replace attribute in XML element if it exists in another XML?

查看:115
本文介绍了XSLT用于XML元素中的replace属性(如果它存在于另一个XML中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个文件

catalog.xml

catalog.xml

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <CD Title="Still got the blues" vinyl="unknown"/>
    <CD Title="When a man loves a woman" vinyl="unknown"/>
</catalog>

vinyl.xml

vinyl.xml

<?xml version="1.0" encoding="UTF-8"?>
<Vinyl>
    <Album>
        <Title>When a man loves a woman</Title>
        <Vinyl>Yes</Vinyl>
    </Album>
</Vinyl>

如何使用xslt生成此类output.xml?

How to produce such output.xml with xslt?

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <CD Title="Still got the blues" vinyl="unknown"/>
    <CD Title="When a man loves a woman" vinyl="yes"/>***   
</catalog>

***标记此行,因为它在output.xml中已更改

***mark this line becouse it changed in output.xml

推荐答案

以下转换使用 catalog.xml 作为输入,并使用document()加载 vinyl.xml .只需进行简单的测试即可执行合并.

The following transform, uses catalog.xml as input and loads vinyl.xml using document(). It performs the merge just by making a simple test.

[XSLT 1.0]

[XSLT 1.0]

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output indent="yes"/>
    <xsl:variable name="vinyl" select="document('test_i2.xml')"/>

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

    <xsl:template match="@vinyl">
        <xsl:attribute name="vinyl">
            <xsl:variable name="test" select="
                 $vinyl/Vinyl/Album[Title=current()/../@Title]/Vinyl"/>
            <xsl:choose>
                <xsl:when test="$test">
                    <xsl:value-of select="$test"/>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:value-of select="."/>
                </xsl:otherwise>
            </xsl:choose>
        </xsl:attribute>
    </xsl:template>

</xsl:stylesheet>


此属性模板的即时性较差,但它利用了纯XPath:


This template for the attribute is less immediate, but it exploits pure XPath:

<xsl:template match="@vinyl">
    <xsl:attribute name="vinyl">
        <xsl:value-of select="
          $vinyl/Vinyl/Album[Title=current()/../@Title]/Vinyl
          |
          self::node()[count($vinyl/Vinyl/Album[Title=current()/../@Title])=0]"/>
    </xsl:attribute>
</xsl:template>

这篇关于XSLT用于XML元素中的replace属性(如果它存在于另一个XML中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆