使用 XSLT 复制 XML 中的所有节点,支持特殊情况

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5876382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 14:41:32  来源:igfitidea点击:

Using XSLT to copy all nodes in XML, with support for special cases

xmlxslt

提问by del.ave

Say I have a large XML file that the following structure:

假设我有一个大型 XML 文件,其结构如下:

<MyXml>
  <Data1>
    <Node1>1234</Node1>
    <Node2>abc<Node2>
    <Node3>gfdf</Node3>
    ...
    <Node10000>more text</Node10000>
  </Data1>
  <Data2>
    ...
  </Data2>
</MyXml>

I want to transform this XML into another XML that looks exactly the same, but has a certain string concatinated to a certain node, say Node766. I am using an XSLT of course and wondering how I can tell it to copy everyhing as-is except for Node766, where I have to do something before outputing it.

我想将此 XML 转换为另一个看起来完全相同的 XML,但将某个字符串连接到某个节点,例如Node766。我当然正在使用 XSLT,想知道如何告诉它按原样复制除Node766之外的所有内容,我必须在输出它之前做一些事情。

回答by Mads Hansen

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<!--Identity template, 
        provides default behavior that copies all content into the output -->
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!--More specific template for Node766 that provides custom behavior -->
    <xsl:template match="Node766">  
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
            <!--Do something special for Node766, like add a certain string-->
            <xsl:text> add some text </xsl:text>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

回答by Don Roby

Start with an identity transform, and include a template match for your exception.

身份转换开始,并为您的异常包含模板匹配。