【问题标题】:xslt copy child note and add extra nodesxslt 复制子注释并添加额外的节点
【发布时间】:2018-04-23 19:31:22
【问题描述】:

对于以下xml:

<root>
    <employees>
        <employee>
            <Name>ABC</Name>
            <Dept>CS</Dept>
            <Designation>sse</Designation>
        </employee>
    </employees>
</root>

我用这个 xslt:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <!-- Identity transform -->
    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Name">
        <xsl:copy-of select="."/>
        <Age>34</Age>
    </xsl:template>

    <xsl:template match="Dept">
       <xsl:copy-of select="."/>
        <Domain>Insurance</Domain>
    </xsl:template>
</xsl:stylesheet>

我想实现如下输出

   <employee>
       <Name>ABC</Name>
       <Age>34</Age>
       <Dept>CS</Dept>
       <Domain>Insurance</Domain>
       <Designation>sse</Designation>
   </employee>

我不知道我应该使用什么 xpath 来将结果仅限于员工节点。

【问题讨论】:

    标签: xslt xpath copy


    【解决方案1】:

    嗯,处理从/ 表示的文档节点(根节点)开始,因此如果您编写模板

    <xsl:template match="/">
      <xsl:apply-templates select="//employee"/>
    </xsl:template>
    

    您仅使用其余模板处理文档的任何 employee 后代。

    请参阅https://xsltfiddle.liberty-development.net/pPqsHT6 以获取集成到您的样式表中的上述建议的工作演示,整个代码是

    <xsl:stylesheet
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        version="1.0">
    
        <xsl:output indent="yes"/>
        <xsl:strip-space elements="*"/>
    
        <!-- Identity transform -->
        <xsl:template match="@* | node()">
            <xsl:copy>
                <xsl:apply-templates select="@* | node()"/>
            </xsl:copy>
        </xsl:template>
    
        <xsl:template match="Name">
            <xsl:copy-of select="."/>
            <Age>34</Age>
        </xsl:template>
    
        <xsl:template match="Dept">
           <xsl:copy-of select="."/>
            <Domain>Insurance</Domain>
        </xsl:template>
    
        <xsl:template match="/">
          <xsl:apply-templates select="//employee"/>
        </xsl:template>
    
    </xsl:stylesheet>
    

    【讨论】:

    • 看起来不错我应该添加什么以使输出被 节点包围(希望避免硬编码)
    • 您可以将我发布的模板添加到您拥有的样式表中,并添加&lt;xsl:output indent="yes"/&gt;&lt;xsl:strip-space elements="*"/&gt;,这足以得到您想要的结果。不确定您要在哪里避免使用元素名称employee
    猜你喜欢
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-17
    • 2018-07-22
    • 2014-05-25
    相关资源
    最近更新 更多