【问题标题】:copy node attributes to parent node将节点属性复制到父节点
【发布时间】:2010-09-08 14:13:06
【问题描述】:

我正在使用 PHP5,我需要将 XML 转换为以下形式:

<section>
      <heading>
            <line absolutePage="4" page="2" num="35">A Heading</line>
      </heading>
      <subsection type="type1">
            <heading label="3">
                  <line absolutePage="4" page="2" num="36">A Subheading</line>
            </heading>
            <content/>
      </subsection>
</section>

变成这样:

<section name="A Heading">
      <heading>
            <line absolutePage="4" page="2" num="35">A Heading</line>
      </heading>
      <subsection type="type1" label="3" name="A Subheading">
            <heading label="3">
                  <line absolutePage="4" page="2" num="36">A Subheading</line>
            </heading>
            <content/>
      </subsection>
</section>

请注意,label 属性已从标题属性复制到父元素。

还添加了heading/line 元素的文本作为heading 父节点的属性。

【问题讨论】:

    标签: php xml xslt


    【解决方案1】:

    这个样式表:

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
        <xsl:template match="@*|node()">
            <xsl:copy>
                <xsl:apply-templates select="@*|node()"/>
            </xsl:copy>
        </xsl:template>
        <xsl:template match="subsection">
            <subsection label="{heading/@label}" name="{heading/line}">
                <xsl:apply-templates select="@*|node()"/>
            </subsection>
        </xsl:template>
        <xsl:template match="section">
            <section name="{heading/line}">
                <xsl:apply-templates select="@*|node()"/>
            </section>
        </xsl:template>
    </xsl:stylesheet>
    

    输出:

    <section name="A Heading">
        <heading>
            <line absolutePage="4" page="2" num="35">A Heading</line>
        </heading>
        <subsection label="3" name="A Subheading" type="type1">
            <heading label="3">
                <line absolutePage="4" page="2" num="36">A Subheading</line>
            </heading>
            <content></content>
        </subsection>
    </section>
    

    注意:只要有可能使用文字结果元素和属性值模板,就使用它。这使代码紧凑而快速。如果您想要更一般的答案,请澄清一下。

    编辑:错过section/@name。当然,如果空字符串section/@label 不打扰你,你可以使用section|subsection 模式匹配。

    【讨论】:

    • @Alejandro,谢谢,效果很好,只需为“部分”添加 OR 匹配,这是缺失的。 :)
    • @Benjamin Ortuzar:你很高兴。我也更新了答案。
    • +1 用于使用和覆盖身份转换以及使用 AVT
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 2015-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    相关资源
    最近更新 更多