【问题标题】:Does XSLT support Clark notation?XSLT 是否支持 Clark 表示法?
【发布时间】:2019-03-15 09:21:14
【问题描述】:

最近,我了解了Clark notation 在 XML 中的含义。如果 XML 看起来像这样:

<srw:searchRetrieveResponse 
 xmlns:srw="http://www.loc.gov/zing/srw/" 
 ...
  <srw:record>
    ... 
  <dc:title>The C programming language</dc:title>
    ...
  </srw:record>

在 Python 中使用lxml,可以这样解析:

record_title = r.find('.//{http://purl.org/dc/elements/1.1/}title')

.//{namespace uri}tag name 的构造对我来说是新的。我认为它对您不熟悉的数据集非常有用,因为您只需要知道名称空间 uri(位于 XML 标头中)、前缀和标签名称即可找到它。因此,您无需了解 XML 树的方式。

现在,我通常使用浏览器为 XML 编写 XSL:只需在示例 XML 文件的顶部指定 XSL 表,双击它,浏览器就会显示 XSL 是由它构成的。那么我可以在 XSL/XSLT 中使用 Clark 表示法吗?据我所知,答案是否定的。一些谷歌搜索让我找到了支持它的 PHP 和 Perl 库,但显然 XSLT 不支持。

我错过了什么吗?如果我不支持,那么 XSLT 不支持它的原因可能是什么?

【问题讨论】:

  • lxml 方法确实简化了事情。但是,请注意 r.find will only return the first matching element。您至少需要知道文件中存在多少匹配元素,以及您想要哪一个。
  • 是的,我知道。我简化了代码以仅显示符号。完整版代码遍历所有records,其中每个record只有一个title

标签: xml xslt


【解决方案1】:

好吧,任何 XSLT/XPath 版本 (https://www.w3.org/TR/xpath-10/#path-abbrev) 都支持类似 .// 的路径,或者说以 .// 开头的路径更好。

对于基于 Clark 表示法的标准化支持,您需要转向 XPath/XSLT 3 https://www.w3.org/TR/xpath-31/#doc-xpath31-URIQualifiedName,其中使用 Q{http://example.com}foo 来选择命名空间 http://example.com 中具有本地名称 foo 的元素。

当然,该语法和您的语法都没有使用任何前缀,它直接使用命名空间而不是任何前缀。使用前缀,例如pf:foo 在任何版本的 XSLT/XPath 中都受支持,在 XSLT 中,您只需确保样式表将前缀与例如xmlns:pf="http://example.com" 到正确的命名空间,使用 XPath 取决于特定的 API 是否以及如何做到这一点。

这是一个基于您的输入的示例,用于显示您在 XSLT 3 中的一些选项:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

    <xsl:output indent="yes"/>

    <xsl:template match="/">
        <four-ways-to-select>
            <enhanced-qname>
                <xsl:copy-of select="//Q{http://purl.org/dc/elements/1.1/}title"/>
            </enhanced-qname>
            <namespace-declaration>
                <xsl:copy-of select="//dc:title" xmlns:dc="http://purl.org/dc/elements/1.1/"/>
            </namespace-declaration>
            <xpath-default-namespace>
                <xsl:copy-of select="//title" xpath-default-namespace="http://purl.org/dc/elements/1.1/"/>
            </xpath-default-namespace>
            <namespace-wildcard>
                <xsl:copy-of select="//*:title"/>
            </namespace-wildcard>
        </four-ways-to-select>
    </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/3NJ38Z2

【讨论】:

    【解决方案2】:

    你的例子中的符号

    './/{http://purl.org/dc/elements/1.1/}title'
    

    任何版本的 XPath 都不支持,但 XPath 3.0 提供了非常相似的功能,即

    './/Q{http://purl.org/dc/elements/1.1/}title'
    

    不使用 Clark 表示法不变的原因是当时有许多竞争提案以“{”开头的表达式,包括 JSONiq 中的映射、XQuery 脚本语言中的语句块和短格式内联函数;在 XSLT 属性值模板中使用“{”也存在混淆的风险。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2019-09-12
      • 2021-10-20
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多