首页 文章

XSLT转换XHTML文档

提问于
浏览
2

我是XSLT的新手,但我建议将其作为完成特定任务的一种方式 . 我有一堆xhtml文件,我想删除侧边栏 . 侧边栏包含在<div class =“foo”>元素中 .

我可以使用此答案中的说明成功执行身份转换:How to remove elements from xml using xslt with stylesheet and xsltproc?但我似乎无法匹配我想要删除的元素 . 也许这是因为它们不是顶级元素,就像我发现的这个设计模式的每个例子中一样?

有人可以解释从身份转换中删除<div class =“foo”>及其所有子节点的正确方法吗?

1 回答

  • 4

    由于源XHTML文件中存在默认(xhtml)命名空间(您没有向我们展示,因此这是最好的猜测),很可能会出现您的问题 .

    有人可以解释从身份转换中删除及其所有孩子的正确方法吗?

    Here is how to do this in case a default namespace is present

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     xmlns:xhtml="http://www.w3.org/1999/xhtml">
     <xsl:output 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="xhtml:div[@class='foo']"/>
    </xsl:stylesheet>
    

    When this transformation is applied on the following XHTML document

    <html xmlns="http://www.w3.org/1999/xhtml">
        <div class="class1">
            <p>Text1</p>
        </div>
        <div class="foo">
            <p>Text foo</p>
        </div>
        <div class="class2">
            <p>Text2</p>
        </div>
    </html>
    

    the wanted, correct result is produced

    <html xmlns="http://www.w3.org/1999/xhtml">
       <div class="class1">
          <p>Text1</p>
       </div>
       <div class="class2">
          <p>Text2</p>
       </div>
    </html>
    

    Using a namespace prefix in the match expression of the template is necessary ,因为XPath认为"no namespace"中的任何未加前缀的名称和带有非前缀名称的匹配表达式与任何节点都不匹配,因为它指定了"no namspace"中的节点,但源文档的所有节点都在XHTML名称空间中 .

    In case there is no default namespace in the source document, the transformation can be simplified

    When this transformation is applied on the following XML document (请注意,它没有定义默认命名空间):

    <html>
        <div class="class1">
            <p>Text1</p>
        </div>
        <div class="foo">
            <p>Text foo</p>
        </div>
        <div class="class2">
            <p>Text2</p>
        </div>
    </html>
    

    the wanted, correct result is produced

    <html>
       <div class="class1">
          <p>Text1</p>
       </div>
       <div class="class2">
          <p>Text2</p>
       </div>
    </html>
    

    Both transformation use the identity rule 复制文档 and another template, which overrides the identity rule for nodes matching "div[@class='foo']" 的任何节点 . 第二个模板为空(没有主体),这意味着匹配的节点和根植于其中的子树根本不被处理(被忽略),因此不会出现在输出中 .

相关问题