Создание вложенной древовидной структуры от пути в XSLT

Можно сделать это использование xlrd пакет.

from xlrd import open_workbook

book = open_workbook("file.xls", formatting_info=True)
sheets = book.sheet_names()
for index, sh in enumerate(sheets):
    sheet = book.sheet_by_index(index)
    rows, cols = sheet.nrows, sheet.ncols
    for row in range(rows):
        for col in range(cols):
            thecell = sheet.cell(row, col)      
            xfx = sheet.cell_xf_index(row, col)
            xf = book.xf_list[xfx]
            bgx = xf.background.pattern_colour_index
            print(bgx)
9
задан Tomalak 23 February 2010 в 10:30
поделиться

1 ответ

Конечно, нет проблем:

<xsl:stylesheet 
  version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>

  <xsl:output indent="yes" />

  <xsl:template match="/data">
    <!-- copy the document element -->
    <xsl:copy>
      <!-- That's where we start: all "record" nodes that have no "\". -->
      <xsl:apply-templates mode="recurse" select="/data/record[
        not(contains(@Name, '\'))
      ]" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="record" mode="recurse">
    <xsl:param name="starting-path" select="''" />

    <!-- The record node and its ID attribute can be copied. --> 
    <xsl:copy>
      <xsl:copy-of select="@ID" />

      <!-- Create the new "name" attribute. -->
      <xsl:attribute name="Name">
        <xsl:value-of select="substring-after(@Name, $starting-path)" />
      </xsl:attribute>

      <!-- Append a backslash to the current path. -->
      <xsl:variable name="current-path" select="concat(@Name, '\')" />

      <!-- Select all "record" nodes that are one level deeper... -->
      <xsl:variable name="children" select="/data/record[
        starts-with(@Name, $current-path)
        and
        not(contains(substring-after(@Name, $current-path), '\'))
      ]" />

      <!-- ...and apply this template to them. -->
      <xsl:apply-templates mode="recurse" select="$children">
        <xsl:with-param name="starting-path" select="$current-path" />
      </xsl:apply-templates>
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Вывод в моей системе:

<data>
  <record ID="26" Name="category 1">
    <record ID="24" Name="sub category 1">
      <record ID="25" Name="sub category 2"></record>
      <record ID="27" Name="sub category 3"></record>
    </record>
  </record>
</data>

Обратите внимание, что все решение основано на предположении, что все пути являются каноническими и не содержат завершающих обратных косых черт.

Также обратите внимание, что любые несопоставленные / потерянные элементы «записи» не будут в выводе (если, конечно, они не находятся на корневом уровне).

Еще одна вещь: режим шаблона («рекурсивный») не является строго нужно. Я включил его, потому что шаблон делает что-то особенное, и есть вероятность, что в вашем решении есть другой шаблон, который соответствует узлам «записи». В этом случае этот раствор можно добавить, ничего не нарушая. Для автономного решения режимы шаблона могут быть отключены в любое время.

О, и последнее: если вы хотите, чтобы результирующий документ был упорядочен по имени, включить элемент с (оба вхождения), например:

<xsl:apply-templates select="...">
  <xsl:sort select="@Name" data-type="text" order="ascending" />
</xsl:apply-templates>
18
ответ дан 4 December 2019 в 11:44
поделиться
Другие вопросы по тегам:

Похожие вопросы: