1

私は C++ および C# アプリケーションで XPath を少し実行しましたが、実際に XSLT で直接使用するのはこれが初めてです。次のような形式の XML ファイルがあります。

<topLevel>
  <foo>
    <bar>prefix1_Taxi</bar>
    ...
  </foo>
  <foo>
    <bar>prefix1_SchoolBus</bar>
    ...
  </foo>
  ...
  <foo>
    <bar>prefix2_Taxi</bar>
    ...
  </foo>
  <foo>
    <bar>prefix2_SchoolBus</bar>
    ...
  </foo>
</topLevel>

まず、"prefix1_" で始まる<foo>要素を持つ要素のみを選択します。<bar>これはうまくいくようです:

<xsl:for-each select="foo[bar[starts-with(., 'prefix1_')]]">

   <!-- Style and format the values from child elements of the "prefix1_" <foo> -->

</xsl:for-each>

for-each次に、ブロック内から<foo>、対応する「prefix2_」要素を含む要素を選択します。次に、適切と思われるデータをそれぞれから引き出したいと思います。

たとえば、が「prefix1_Taxi」を選択した場合、「prefix2_Taxi」要素を含む要素をfor-each選択したいとします。foobar

<xsl:for-each select="foo[bar[starts-with(., 'prefix1_')]]">

   <!-- Retrieve the corresponding "prefix2_" foo -->
   <!-- Style and format the values from child elements of the "prefix1_" <foo> -->
   <!-- Style and format the values from child elements of the "prefix2_" <foo> -->

</xsl:for-each>

残念ながら、これについてどうすればよいかわかりません。従来のプログラムでは、次の疑似コードのようなことを行います。

String buf = barElement.Name.Replace("prefix1_", String.Empty);
XmlNode otherFoo = document.SelectSingleNode("foo[bar[" + buf + "]]");

ただし、XSLT は値の取得とデータの操作に関して明らかに異なるパラダイムで動作するため、私は古い考え方から抜け出そうとしています。

XSLT に関するいくつかのグーグル検索から収集したものを使用して、かなり醜いものを思いつきました。

  1. テキストで始まるバーを含む foo 要素を選択します。

    foo[bar[starts-with(., ...)

  2. <bar>現在の要素の「prefix1_」を置き換えます。

    replace(<xsl:value-of select='bar'/>, 'prefix1_', '')

これはかなり醜い混乱を引き起こします:

<xsl:value-of select="foo[bar[starts-with(., replace(<xsl:value-of select='bar'/>, 'prefix1_', ''))]]" />

<xsl:value-of>また、要素が正しくないことも確信しています。

どうすればいいですか?XSLT でこの概念を表現する方法について、いくつかの核となる概念が欠けているのではないかと思います。私はXSLTのw3.org ページをめくっていますが、まだまだ勉強と練習が必要です。

4

2 に答える 2

2

この XSL スタイルシートはfoo、"prefix2" を含む要素の処理について、ある程度の柔軟性を提供します。

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

  <!-- Matches the top level element and selects the children with prefix1 text. -->
  <xsl:template match="topLevel">
    <xsl:copy>
      <xsl:apply-templates select="foo[bar[starts-with(., 'prefix1_')]]"/>
    </xsl:copy>
  </xsl:template>

  <!-- We're at a foo element with prefix1 text. Select the siblings of the 
       same vehicle type, with prefix2 text. -->
  <xsl:template match="foo[bar[starts-with(., 'prefix1_')]]">
    <xsl:variable name="vehicle" select="substring-after(bar, 'prefix1_')"/>
    <xsl:apply-templates select="../foo[bar = concat('prefix2_', $vehicle)]"/>
  </xsl:template>

  <!-- In this template, you can do whatever you want with the foo element containing
       the prefix2 vehicles. This example just copies the element and its children. -->
  <xsl:template match="foo[bar[starts-with(., 'prefix2_')]]">
    <xsl:copy-of select="."/>
  </xsl:template>
</xsl:stylesheet>
于 2013-08-09T22:12:46.533 に答える