开发者

xsl to remove comments from all the nodes

I am using xsl script to remove commen开发者_JAVA百科ts from all the portion of the xml. It is actually removing the comments which are in parent node but not from the other interior nodes.

[edited]

Updating the question. My requirement is to remove all the comments from entire XML document.


This transformation:

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

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

when applied on any XML document containing comment nodes, like this:

<!-- foo -->
<a>
   <!-- bar -->
   <b>
      <c><!-- baz --></c>
   </b>
</a>

produces the wanted result (the same document with the comment nodes stripped-off):

<a>
    <b>
        <c/>
    </b>
</a>

Do note: The use of the most fundamental and powerful XSLT design pattern -- the use and overriding of the identity rule.


It sounds like you want to copy only the comments from the input XML. And you're saying that your stylesheet copies certain comments but not others? When you say "comments which are in parent node", do you mean comments that are children of the root node (i.e. outside of all elements)?

When I try this stylesheet it works fine. Specifically the XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
   <xsl:template match="/">
      <comments>
         <xsl:for-each select="//comment()">
            <comment><xsl:value-of select="."/></comment>
         </xsl:for-each>
      </comments>
   </xsl:template>
</xsl:stylesheet>

run against the input

<?xml version="1.0" encoding="UTF-8"?>
<!-- foo -->
<a>
   <!-- bar -->
   <b>
      <c><!-- baz --></c>
   </b>
</a>

gives the output

<?xml version="1.0" encoding="utf-8"?>
<comments>
   <comment> foo </comment>
   <comment> bar </comment>
   <comment> baz </comment>
</comments>

If this is not the behavior you wanted, or if yours still doesn't work on your input, can you post your whole stylesheet and a sample of your input XML, and show what the current output is? Also what XSLT processor are you using?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜