我是XSLT的新手,但我建议将其作为完成特定任务的一种方式 . 我有一堆xhtml文件,我想删除侧边栏 . 侧边栏包含在<div class =“foo”>元素中 .
我可以使用此答案中的说明成功执行身份转换:How to remove elements from xml using xslt with stylesheet and xsltproc?但我似乎无法匹配我想要删除的元素 . 也许这是因为它们不是顶级元素,就像我发现的这个设计模式的每个例子中一样?
有人可以解释从身份转换中删除<div class =“foo”>及其所有子节点的正确方法吗?
1 回答
由于源XHTML文件中存在默认(xhtml)命名空间(您没有向我们展示,因此这是最好的猜测),很可能会出现您的问题 .
Here is how to do this in case a default namespace is present :
When this transformation is applied on the following XHTML document :
the wanted, correct result is produced :
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 (请注意,它没有定义默认命名空间):
the wanted, correct result is produced :
Both transformation use the identity rule 复制文档 and another template, which overrides the identity rule for nodes matching "div[@class='foo']" 的任何节点 . 第二个模板为空(没有主体),这意味着匹配的节点和根植于其中的子树根本不被处理(被忽略),因此不会出现在输出中 .