1

子要素がまだ同じ属性を持っていない場合にのみ、子要素に属性を渡すにはどうすればよいですか?

XML:

<section>
    <container attribute1="container1" attribute2="container2">
         <p attribute1="test3"/>
         <ol attribute2="test4"/>
    <container>
<section/>

出力は次のようになります。

<section>
    <p attribute1="test3" attribute2="test2"/>
    <ol attribute1="container1" attribute2="test4"/>
</section>

これは私が試したものです:

<xsl:template match="container">
    <xsl:apply-templates mode="passAttributeToChild"/>
</xsl:template>

<xsl:template match="*" mode="passAttributeToChildren">
    <xsl:element name="{name()}">
        <xsl:for-each select="@*">
             <xsl:choose>
                  <xsl:when test="name() = name(../@*)"/>
                  <xsl:otherwise>
                      <xsl:copy-of select="."/>
                  </xsl:otherwise>
             </xsl:choose>
        </xsl:for-each>
        <xsl:apply-templates select="*|text()"/>
    </xsl:element>
</xsl:template>

どんな助けでも大歓迎です;)事前にありがとう!

4

2 に答える 2

0

複数回宣言された属性は互いに上書きするため、これは簡単です。

<xsl:template match="container/*">
  <xsl:copy>
    <xsl:copy-of select="../@*" /> <!-- take default from parent -->
    <xsl:copy-of select="@*" />    <!-- overwrite if applicable -->
    <xsl:apply-templates />
  </xsl:copy>
</xsl:template>

サンプルが示すように、これはすべての親属性が必要であることを前提としています。もちろん、継承する属性を決定できます。

    <xsl:copy-of select="../@attribute1 | ../@attribute2" />
    <xsl:copy-of select="@attribute1 | @attribute2">
于 2013-08-05T12:06:08.210 に答える
0

これを試して。

<!-- root and static content - container -->
<xsl:template match="/">
    <section>
        <xsl:apply-templates select='section/container/*' />
    </section>
</xsl:template>

<!-- iteration content - child nodes -->
<xsl:template match='*'>
    <xsl:element name='{name()}'>
        <xsl:apply-templates select='@*|parent::*/@*' />
    </xsl:element>
</xsl:template>

<!-- iteration content - attributes -->
<xsl:template match='@*'>
    <xsl:attribute name='{name()}'><xsl:value-of select='.' /></xsl:attribute>
</xsl:template>

各子ノードを出力する際に​​、その属性と親の属性を繰り返し転送します。

<xsl:apply-templates select='@*|parent::*/@*' />

テンプレートは、XML に表示される順序でノードに適用されます。したがって、親 ( container) ノードは (もちろん) 子ノードの前に表示されるため、属性テンプレートによって最初に処理されるのは親の属性です。

これは、子ノード自体のアトリビュートが既に存在する場合、テンプレートが常に子ノード自身のアトリビュートを優先することを意味するため便利です。これは、子ノードが最後に処理され、親からの同じ名前を持つアトリビュートよりも優先されるためです。したがって、親はそれらを覆すことはできません。

この XMLPlaygroundでの作業デモ

于 2013-08-05T10:55:51.907 に答える