首页 > 解决方案 > 将 XML 中的单个值复制到其他 XML 中的两个不同位置

问题描述

我有一个具有这种结构的 XML 文件:

<DetailTxt>
    <Text>
        <span>Some Text</span>
    </Text>
    <TextComplement Kind="Owner" MarkLbl="1">
        <ComplCaption>
            Caption 1
        </ComplCaption>
        <ComplBody>
            Body 1
        </ComplBody>
    </TextComplement>
    <Text>
        <span>More Text</span>
    </Text>
</DetailTxt>

以下是与此处相关的 XSLT 部分:

<xsl:template match="*[local-name() = 'DetailTxt']">
    <xsl:apply-templates select="*[local-name() = 'Text']"/>
</xsl:template>

<xsl:template match="*[local-name() = 'Text']">
    <item name="{local-name()}">
        <richtext>
            <par>
                <run>
                    <xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text>
                    <xsl:apply-templates/>
                    <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text>
                </run>
            </par>
        </richtext>
    </item> 
    <item name="{local-name()}">
       <richtext>
            <par>
                <run>
                    <xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text>
                    <xsl:value-of select="concat('[', ../TextComplement/@Kind, ../TextComplement/@MarkLbl,']')" />
                    <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text>
                </run>
            </par>
        </richtext>
    </item>
</xsl:template>

我希望输出看起来像这样:

<item name="Text">
    <richtext>
        <par>
            <run><![CDATA[
                <span>Some Text</span>
            </p>]]></run>
        </par>
    </richtext>
</item>
<item name="Text">
    <richtext>
        <par>
            <run><![CDATA[[Owner1]]]></run>
        </par>
    </richtext>
</item>

但是使用 TextComplement XPath 的行如下所示:

            <run><![CDATA[[]]]></run>

缺少来自 TextComplement 的所有值。这里的 XPath 有什么问题?

编辑:我完全修改了我的问题,并提出了一个由第一个答案产生的具体问题。这种方法使第一个答案无效,但恕我直言,改进了这个问题。

标签: xslt

解决方案


不确定 XSLT 的外观,但您可以尝试使用concat()获取输出的功能添加以下模板。

<xsl:template match="Text">
    <document version="9.0" form="Form1">
        <item name="{local-name()}">
            <xsl:copy-of select="span" />
        </item>
        <item name="{local-name()}">
            <span>
                <xsl:value-of select="concat('[', ../TextComplement/@Kind, ../TextComplement/@MarkLbl, ']')" />
            </span>
        </item>
    </document>
</xsl:template>

该模板应用于<Text>节点,../用于上一级,然后访问<TextComplement>使用 XPath 的属性。

应用于您的 XML 时模板的输出将如下所示。

<document form="Form1" version="9.0">
    <item name="Text">
        <span>Some Text</span>
    </item>
    <item name="Text">
        <span>[Owner1]</span>
    </item>
</document>

相同的模板也将应用于<Text>具有内容的节点More Text并产生类似的输出。


推荐阅读