首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XML元素中的替换属性的XSLT是否存在于另一个XML中?

XML元素中的替换属性的XSLT是否存在于另一个XML中?
EN

Stack Overflow用户
提问于 2011-08-09 21:35:46
回答 1查看 1.3K关注 0票数 3

我有两个文件

catalog.xml

代码语言:javascript
复制
<?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

代码语言:javascript
复制
<?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?

代码语言:javascript
复制
<?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中已更改

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-08-09 21:49:40

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

XSLT 1.0

代码语言:javascript
复制
<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:

代码语言:javascript
复制
<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>
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6996998

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档