【问题标题】:Move sub nodes into parent attributes with XSLT使用 XSLT 将子节点移动到父属性中
【发布时间】:2010-10-26 22:18:18
【问题描述】:

我有一些包含记录和子记录的 XML,如下所示:

<data>
    <record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00">
        <record jsxid="id0x0b60ff10" string="101"/>
        <record jsxid="id0x0e64d8e8" string="63"/>
        <record jsxid="id0x2fd83f08" string="Y"/>
    </record>
    <record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00">
        <record jsxid="id0x0b60ff10" string="102"/>
        <record jsxid="id0x0e64d8e8" string="77"/>
        <record jsxid="id0x2fd83f08" string="Y"/>
    </record>       
<data>

我需要对其进行转换,以便将子记录的字符串属性作为连续编号的属性带到父记录中,然后丢弃,如下所示:

<data>
    <record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00" 1="101" 2="63" 3="Y"/>
    <record jsxid="id0x0b60fec0" ID="12429070" Created="2008-10-21T03:00:00.0000000-07:00" 1="102" 2="77" 3="Y"/>
<data>

子记录的数量在文档中是任意的,但在同一个文档中保持不变。

有人会这么好心地指出 XSLT 解决方案的方法吗?非常感谢。

【问题讨论】:

    标签: xml xslt


    【解决方案1】:

    这是一个完整的解决方案:

    <xsl:stylesheet version="1.0"
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <!-- By default, recursively copy all nodes unchanged -->
      <xsl:template match="@* | node()">
        <xsl:copy>
          <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
      </xsl:template>
    
      <!-- But don't process any children of <record> (such as whitespace)... -->
      <xsl:template match="record/node()"/>
    
      <!-- ...except for doubly-nested records;
           convert them to attributes, named according to position -->
      <xsl:template match="record/record" priority="1">
        <xsl:variable name="pos">
          <xsl:number/>
        </xsl:variable>
        <xsl:attribute name="r{$pos}">
          <xsl:value-of select="@string"/>
        </xsl:attribute>
      </xsl:template>
    
    </xsl:stylesheet>
    

    请注意,我将您的属性名称更改为“r1”、“r2”等,因为 XML 不允许您以数字开头。

    【讨论】:

      【解决方案2】:

      可能会这样做,在处理顶级 &lt;record&gt; 元素时运行以下 XSLT 的 sn-p:

      <xsl:for-each select="record">
          <xsl:attribute name="{position()}">
              <xsl:value-of select="@string" />
          </xsl:attribute>
      </xsl:for-each>
      

      基本上这会遍历每个子&lt;record&gt; 元素并创建一个描述所需属性的&lt;xsl:attribute&gt; 元素。调用position()函数获取顶层元素内的相对位置:1、2、3等

      这不是一个完整的解决方案;假设您对 XSLT 有一定的了解。

      【讨论】:

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