Добавьте текст в дочерний элемент XML с помощью XSL, сохранив при этом все дочерние элементы и атрибуты дочерних элементов.

Я пытаюсь добавить некоторый текст в абзац на основе атрибута «производительность» его родителя «шаг».

Если шаг помечен как «performance = «необязательный», я бы хотел, чтобы результирующий текст (для второго шага ниже) выглядел так:

"2. (Необязательно) Это шаг 2..."

<procedure>
    <step id="step_lkq_c1l_5j">
        <para>This is step 1, which is required.</para>
    </step>
    <step performance="optional">
        <para>This is step 2, which is optional, unlike <xref linkend="step_lkq_c1l_5j"/>.
            <note>
                <para>I don't want to lose this note in my transformation.</para>
            </note>
        </para>
    </step>
    <step>
        <para>This is step 3.</para>
    </step>
</procedure>

Я попытался использовать Xpath, чтобы сопоставить мой узел и изменить его: <xsl:template match="step[@performance='optional']/child::para[position()=1]">, а затем использовать concat(), чтобы попытаться добавить мой необязательный текст, но я потерял бы ссылку xref (возможно, потому, что concat() не учитывает дочерние элементы и атрибуты?)

Я приблизился к тому, что хочу, используя следующую настройку xsl, но (необязательный) текст находится за пределами абзаца, и это опускает текст шага вниз по строке и иногда разрывается с содержимым страницы. Я действительно хочу, чтобы сгенерированный текст находился внутри первого абзаца.

У кого-нибудь есть предложение?

    <!-- Add "(Optional) " to steps that have the performance="optional" attribute set -->
<xsl:template match="procedure/step|substeps/step">
    <xsl:variable name="id">
        <xsl:call-template name="object.id"/>
    </xsl:variable>

    <xsl:variable name="keep.together">
        <xsl:call-template name="pi.dbfo_keep-together"/>
    </xsl:variable>

    <fo:list-item xsl:use-attribute-sets="list.item.spacing">
        <xsl:if test="$keep.together != ''">
            <xsl:attribute name="keep-together.within-column"><xsl:value-of
                select="$keep.together"/></xsl:attribute>
        </xsl:if>

        <fo:list-item-label end-indent="label-end()">
            <fo:block id="{$id}">
                <!-- dwc: fix for one step procedures. Use a bullet if there's no step 2 -->
                <xsl:choose>
                    <xsl:when test="count(../step) = 1">
                        <xsl:text>&#x2022;</xsl:text>
                    </xsl:when>
                    <xsl:otherwise>
                        <xsl:apply-templates select="." mode="number">
                            <xsl:with-param name="recursive" select="0"/>
                        </xsl:apply-templates>.
                    </xsl:otherwise>
                </xsl:choose>
            </fo:block>
        </fo:list-item-label>
        <xsl:choose>
            <xsl:when test="@performance='optional'">
                <fo:list-item-body start-indent="body-start()">
                    <fo:block>
                        <xsl:text>(Optional) </xsl:text>
                        <xsl:apply-templates/>
                    </fo:block>
                </fo:list-item-body>
            </xsl:when>
            <xsl:otherwise>
                <fo:list-item-body start-indent="body-start()">
                    <fo:block>
                        <xsl:apply-templates/>
                    </fo:block>
                </fo:list-item-body>
            </xsl:otherwise>
        </xsl:choose>
    </fo:list-item>
</xsl:template>

person Eric N    schedule 09.04.2013    source источник
comment
У вас есть шаблон, соответствующий вашим para элементам?   -  person Tim C    schedule 09.04.2013


Ответы (1)


Из вашего вопроса неясно, хотите ли вы просто знать, как добавить текст «(Необязательно)», или хотите ли вы, чтобы он был включен в ваш XSL-FO, или вам нужен «2». также нумерация. Вот простой ответ для первого случая:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="step[@performance = 'optional']/para/text()[1]">
    <xsl:value-of select="concat('(Optional) ', normalize-space())"/>
  </xsl:template>
</xsl:stylesheet>

При запуске на вашем образце ввода это производит:

<procedure>
  <step id="step_lkq_c1l_5j">
    <para>This is step 1, which is required.</para>
  </step>
  <step performance="optional">
    <para>(Optional) This is step 2, which is optional, unlike<xref linkend="step_lkq_c1l_5j" />.
      <note><para>I don't want to lose this note in my transformation.</para></note></para>
  </step>
  <step>
    <para>This is step 3.</para>
  </step>
</procedure>

Чтобы получить нумерацию, вы можете заменить этот второй шаблон следующим:

  <xsl:template match="step[@performance = 'optional']/para/text()[1]">
    <xsl:variable name="sequence">
      <xsl:number level="multiple" count="step"/>
    </xsl:variable>
    <xsl:value-of select="concat($sequence, '. (Optional) ', normalize-space())"/>
  </xsl:template>

Что производит:

<procedure>
  <step id="step_lkq_c1l_5j">
    <para>This is step 1, which is required.</para>
  </step>
  <step performance="optional">
    <para>2. (Optional) This is step 2, which is optional, unlike<xref linkend="step_lkq_c1l_5j" />.
      <note><para>I don't want to lose this note in my transformation.</para></note></para>
  </step>
  <step>
    <para>This is step 3.</para>
  </step>
</procedure>

И чтобы пронумеровать все шаги, вы можете заменить тот же шаблон на это:

  <xsl:template match="step/para/text()[1]">
    <xsl:variable name="sequence">
      <xsl:number level="multiple" count="step"/>
    </xsl:variable>
    <xsl:value-of select="concat($sequence, '. ')"/>

    <xsl:if test="../../@performance = 'optional'">
      <xsl:text>(Optional) </xsl:text>
    </xsl:if>

    <xsl:value-of select="normalize-space()"/>
  </xsl:template>

Что производит:

<procedure>
  <step id="step_lkq_c1l_5j">
    <para>1. This is step 1, which is required.</para>
  </step>
  <step performance="optional">
    <para>2. (Optional) This is step 2, which is optional, unlike<xref linkend="step_lkq_c1l_5j" />.
      <note><para>I don't want to lose this note in my transformation.</para></note></para>
  </step>
  <step>
    <para>3. This is step 3.</para>
  </step>
</procedure>
person JLRishe    schedule 09.04.2013