1

私は XSLT に不慣れで、些細に見える問題の解決策を見つけようと何時間も費やしてきました。

次のようなリストを含む xml ドキュメントがあります。

  <Header>
    <URLList>
      <URLItem type="type1">
        <URL></URL>
      </URLItem>
      <URLItem type="type2">
        <URL>2</URL>
      </URLItem>
    </URLList>
  </Header>

存在しない場合は、「ID」要素を各 URLItem に追加する必要があります。ID 要素の値は、インクリメントされた値である必要があります。

xml は最終的に次のようになります。

  <Header>
    <URLList>
      <URLItem type="type1">
        <ID>1</ID>
        <URL></URL>
      </URLItem>
      <URLItem type="type2">
        <ID>2</ID>
        <URL>2</URL>
      </URLItem>
    </URLList>
  </Header>

いろいろ試してみましたが、うまく動かせませんでした。

たとえば、テンプレートを使用してリストを照合しようとすると、正しいインクリメント値を取得できません。ID 値は [2,4] ですが、[1,2] ではありません... これは xslt です:

  <xsl:template match="/Header/URLList/URLItem[not(child::ID)]">
    <xsl:copy>
      <ID> <xsl:value-of select="position()"/></ID>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

また、次のような for-each ループを使用しようとしています。

  <xsl:template match="/Header/URLList">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
    <xsl:for-each select="/Header/URLList/URLItem">
        <xsl:if test="not(ID)">
          <xsl:element name="ID"><xsl:value-of select="position()" /></xsl:element>
        </xsl:if>
    </xsl:for-each>
  </xsl:template>

このように、インクリメントは正しいように見えますが、新しい ID 要素が親ノードに表示されます。それらを URLItem 要素の子としてアタッチする方法を見つけることができませんでした。

どんな助けでも大歓迎です。

4

2 に答える 2

3

それ以外の

  <xsl:template match="/Header/URLList/URLItem[not(child::ID)]">
    <xsl:copy>
      <ID> <xsl:value-of select="position()"/></ID>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

使用する

  <xsl:template match="/Header/URLList/URLItem[not(child::ID)]">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <ID><xsl:number/></ID>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
于 2012-10-29T16:02:51.780 に答える
0
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml"/>
<xsl:template match="/">
<Header>
<xsl:apply-templates select="//URLList"/>
</Header>
</xsl:template>
<xsl:template match="URLList">
<URLList>
<xsl:for-each select="URLItem[not(child::ID)]">
<xsl:copy>
    <xsl:apply-templates select="@*"/>
      <ID> <xsl:value-of select="position()"/></ID>
      <xsl:copy-of select="URL"/>
    </xsl:copy>
  </xsl:for-each>
  </URLList>
  </xsl:template>
  <xsl:template match="@*">
<xsl:copy-of select="."/>
  </xsl:template>
</xsl:stylesheet>
于 2012-10-29T16:38:54.590 に答える