【问题标题】:XSLT output child elements with different namespaceXSLT 输出具有不同命名空间的子元素
【发布时间】:2018-05-14 23:55:51
【问题描述】:

我在发布之前在谷歌搜索过,但我找不到答案,所以我想在这里发布解决方案,以便对其他开发人员有所帮助。

场景: 样本输入

    <CarYard>
       <Cars>
          <A>honda</A>
          <B>BMW</B>
          <C>AUDI</C>
      </Cars>
   </CarYard>$

如何为元素 A、B、C 生成命名空间 当你在做动态模板匹配时。

【问题讨论】:

    标签: xml xslt


    【解决方案1】:
               <xsl:template match="CarYard">       
                <xsl:apply-templates select="//CarYard/*[1]" mode="addNamespace"/>
            </xsl:element>          
    </xsl:template>
    
    <xsl:template match="node() | @*" mode="addNamespaceToAllChild">
        <xsl:variable name="ELEM_NAME" select="concat('ns1:',local-name())"/>
        <xsl:element name="{$ELEM_NAME}" xmlns:ns1="http://test.namespace/generic">
            <xsl:apply-templates select="@* | node()"/>
        </xsl:element>
    </xsl:template> 
    <xsl:template match="node() | @*" mode="addNamespace">
        <xsl:variable name="ELEM_NAME" select="concat('ns1:',local-name())"/>
        <xsl:element name="{$ELEM_NAME}" xmlns:ns1="http://schemas.test.namespace/generic">
            <xsl:apply-templates select="@* | node()" mode="addNamespaceToAllChild"/>
        </xsl:element>
    </xsl:template>
    

    现在结果输出将是

    <CarYard>
       <ns1:Cars>
          <ns1:A>honda</ns1:A>
          <ns1:B>BMW</ns1:B>
          <ns1:C>AUDI</ns1:C>
      </ns1:Cars>
    

    【讨论】:

    • 您的代码似乎特意将 CarYard 的子代放在一个命名空间 (test.namespace/generic) 中,将孙子放在另一个 (schemas.test.namespace/generic) 和曾孙(如果有任何)其他地方。但这并未反映在您的要求或您显示的示例输出中。
    • 我要补充的另一件事是,您应该尝试通过在 google 上搜索来解决此问题,这有点令人难过。谷歌可以很好地解决一些编程问题,例如追踪特定错误消息的含义,但这并不是学习新编程语言技术的真正方法。给自己买几本好书,然后读一读!
    【解决方案2】:

    输出命名空间元素的有效示例如下所示。

        <xsl:element name="x:include" namespace="http://www.w3.org/2001/XInclude">
            <xsl:apply-templates select="@href"/>
        </xsl:element>
    

    这会产生这样的东西。

    <x:include xmlns:x="http://www.w3.org/2001/XInclude" href="../topics/topic.dita">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-19
      • 2014-02-14
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 1970-01-01
      相关资源
      最近更新 更多