使用 XSLT 作为 XML 预处理器 [英] Using XSLT as an XML pre-processor

查看:47
本文介绍了使用 XSLT 作为 XML 预处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次用 XSLT 或 XML 做任何事情,所以请原谅.我发现 XSLT 网络文档非常简洁.

This is my first time doing anything with XSLT, or XML really, so please excuse me. I've found XSLT web documentation is really terse.

我有一个 XML 文件,我想对其进行处理,以便根据输入的定义集有选择地删除内容.该行为应该类似于处理 ifdef 块的简单代码预处理器.

I have an XML file that I want to process to selectively drop content based on an input set of defines. The behavior should be similar to a simple code pre-processor handling ifdef blocks.

我已经按照下面的方法确定了如何执行此操作,但某些部分(例如内容"变量)似乎不是处理此问题的最佳方法.

I've worked out how to do it as below, but some parts such as the "contents" variable didn't seem like the best way to handle this.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="xml" />
  <xsl:param name="defines-uri" required="yes"/>

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

  <xsl:template match="ifdef">
    <xsl:variable name="contents" select="child::node()"/>
    <xsl:variable name="defines" select="document($defines-uri)/defines"/>
    <xsl:variable name="val" select="@select"/>

    <xsl:for-each select="$defines">
      <xsl:if test="def=$val">
        <xsl:apply-templates select="$contents"/>
      </xsl:if>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

主要问题是在定义中找到匹配项时的应用模板.没有内容,我在输出中得到不同程度转储的定义文档.

The main issue was the apply-templates on the case when a match was found in the defines. Without the contents, I get the defines document dumped to different degrees in the output.

在不进行转换的情况下对 XML 进行预处理的最佳方法是什么?

Whats the best way to do pre-processing of XML without transformation?

推荐答案

对于刚开始接触 XSLT XML 的人来说,您做得非常好.

You're doing really well for someone who's only just beginning with XSLT and XML.

这不是您问题的答案,但我只想说这可能是一个更安全的默认复制"模板:

This isn't an answer to your question, but I just wanted to say that this might be a safer "copy by default" template:

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

您的作品得益于某个默认的内置模板.但是,当您添加更多模板时,您可能会在文本节点(或其他不是元素的东西)方面出现奇怪的行为,因为默认设置的优先级较低.

Yours works by grace of a certain default built-in template. But you might get strange behaviour regarding text nodes (or other things that aren't elements) when you add more templates, since the default has a low priority.

这篇关于使用 XSLT 作为 XML 预处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆