2

XLTS を使用した XML ファイルの解析に問題があります。

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pl">
    <body style="margin-top: 0px;">
    <a name="top"/>
    <a name="menu"> </a>
    <a href="cool html"> </a>
    <table width="100%" cellspacing="0" cellpadding="2" border="0" class="aws_border sortable"/>
    </body>
    </html>

そして、ドキュメント内のノードと他のノード<a name="something"> </a>を保持しながら、すべてのノードを削除する必要があります。<a href>

私が試してみました

    <xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
    <xsl:template match="body"> 
    <xsl:for-each select="a"> 
      <xsl:if test="@href != '' ">
     <xsl:copy-of select="."/> 
    </xsl:if>
         </xsl:for-each> 
    </xsl:template>
    </xsl:stylesheet>

ただし、ノードのみが保持され<a href >、他のすべてのノードが削除されます。

4

1 に答える 1

4

すべてのノードを保持し、いくつかのノードのみを変更すると、常に次のようになります。

  1. ID テンプレートを使用します。他の方法で処理されないすべてのノードをコピー (「保存」) します。
  2. 異なる方法で処理する必要があるノードごとに別のテンプレートを作成します。
  3. を使いたいという衝動に抵抗します<xsl:for-each>。あなたはそれを必要としません。

XSLT:

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

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

  <!-- empty template to remove <a name="..."> specifically -->    
  <xsl:template match="xhtml:a[@name]" />

</xsl:stylesheet>

それでおしまい。

ポイント3は実際にはかなり重要です。<xsl:for-each>あなたが書くすべてのXSLTで避けてください。なじみがあり、役立つように見えますが、そうではありません。これを使用すると、扱いにくく、モノリシックで、再利用が困難な、深くネストされた XSLT コードになる傾向があります。

常に好むよう<xsl:template><xsl:apply-templates>してください<xsl:for-each>

于 2012-10-05T07:00:10.870 に答える