复制除image和span Tag之外的所有内容

时间:2016-09-01 13:24:56

标签: xml xslt

我尝试复制除图像和跨度标记之外的所有内容。 目前,脚本也复制了图像标签。 我该怎么用?

XLST

<xsl:when test="child::img[@src='note.png']">  
   <note>
      <p>
      <xsl:apply-templates select="node()[not(self::span[@class='mark'][not(preceding-sibling::span[@class='mark'])])]"/>
      </p>
      <xsl:apply-templates select="following-sibling::*[1][self::ul]/node()"/>
  </note>        
</xsl:when>

XML来源

<note>
  <p>
    <img src="note.png"/>
    <span class="mark">Text</span>
    Text
  </p>
  <ul>
    <li><p>Text</p></li>
    <li><p>Text</p></li>
  </ul>
</note>

XML Targed

<note>
  <p>
    Text
  </p>
  <ul>
    <li><p>Text</p></li>
    <li><p>Text</p></li>
  </ul>
</note>

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

试试这个:

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

<xsl:strip-space elements="*"/>

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

<xsl:template match="p">
    <xsl:choose>
       <xsl:when test="child::img[@src='note.png']">  
           <p>
             <xsl:apply-templates select="node()[not(self::span[@class='mark'])][not(self::img[@src='note.png'])]"/>
           </p>
       </xsl:when>
       <xsl:otherwise><xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy></xsl:otherwise>
    </xsl:choose>
</xsl:template>

</xsl:stylesheet>

**或**

<xsl:template match="p">
    <xsl:copy>
         <xsl:apply-templates select="node()[not(self::span[@class='mark'])]
                                      [not(self::img[@src='note.png'])]"/>
   </xsl:copy>
</xsl:template>

<强>输出:

<note>
<p>
   Text
</p>
<ul>
  <li>
     <p>Text</p>
  </li>
  <li>
     <p>Text</p>
  </li>
</ul>
</note>

答案 1 :(得分:0)

一般情况下,如果您想进行此类转换,那么请先从身份转换模板

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

然后添加与要删除的节点匹配的空模板,例如

<xsl:template match="img | span"/>

或者

<xsl:template match="img | span[@class = 'mark']"/>

如果只删除具有该类的span元素。