在XSLT期间保留某些html标记

Bil*_*zac 0 html xml xslt

我已经在stackflow上查找了解决方案,但它们似乎都不适合我.这是我的问题.可以说我有以下文字:

资源:

<greatgrandparent>
<grandparent>
    <parent>
         <sibling>
              Hey, im the sibling .
          </sibling>
        <description>
        $300$ <br/> $250 <br/> $200! <br/> <p> Yes, that is right! <br/> You can own a ps3 for only $200 </p>
        </description>
    </parent>
    <parent>
         ... (SAME FORMAT)
    </parent>
       ... (Several more parents)
</grandparent>
</greatgrandparent>
Run Code Online (Sandbox Code Playgroud)

输出:

 <newprice>
        $300$ <br/> $250 <br/> $200! <br/> Yes, that is right! <br/> You can own a ps3 for only $200  
    </newprice>
Run Code Online (Sandbox Code Playgroud)

我似乎找不到办法做到这一点.

目前的XSL:

    <xsl:template match="/">
            <xsl:apply-templates />
        </xsl:template>

        <xsl:template match="greatgrandparents">
            <xsl:apply-templates />
        </xsl:template>

    <xsl:template match = "grandparent">

    <xsl:for-each select = "parent" >
          <newprice>
             <xsl:apply-templates>
           </newprice>
    </xsl:for-each>
    </xsl:template> 

<xsl:template match="description"> 
    <xsl:element name="newprice"> 
       <xsl:apply-templates/> 
    </xsl:element> 
</xsl:template> 

<xsl:template match="p"> 
   <xsl:apply-templates/> 
</xsl:template> 
Run Code Online (Sandbox Code Playgroud)

Jon*_*n W 5

使用模板定义特定元素的行为

<!-- after standard identity template -->

<xsl:template match="description">
    <xsl:element name="newprice">
       <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="p">
   <xsl:apply-templates/>
</xsl:template>
Run Code Online (Sandbox Code Playgroud)

第一个模板说交换descriptionnewprice.第二个人说要忽略这个p元素.

如果您不熟悉身份模板,请在此处查看一些示例.

编辑:鉴于新的例子,我们可以看到你只想提取description元素及其内容.请注意,模板操作以模板开头match="/".我们可以在样式表开始的地方使用此控件,从而跳过我们想要过滤掉的大部分痞子.

改为<xsl:template match="/">更像是:

    <xsl:template match="/">
        <xsl:apply-templates select="//description"/>   
        <!-- use a more specific XPath if you can -->
    </xsl:template>
Run Code Online (Sandbox Code Playgroud)

所以我们的解决方案看起来像这样:

<xsl:stylesheet 
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
    exclude-result-prefixes="xs">

<xsl:template match="/">
    <xsl:apply-templates select="//description" />
</xsl:template>

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

<xsl:template match="description">
    <xsl:element name="newprice">
       <xsl:apply-templates/>
    </xsl:element>
</xsl:template>

<xsl:template match="p">
   <xsl:apply-templates/>
</xsl:template>

</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)