且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 XSLT 将子节点移动到父属性中

更新时间:2023-02-02 08:29:20

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

Here's a complete solution:

<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 不允许您以数字开头.

Note that I changed the name of your attributes to "r1", "r2", etc., because XML doesn't allow you to start a name with a number.