【问题标题】:xslt read/print namespace at declarationxslt 在声明时读取/打印命名空间
【发布时间】:2015-05-04 07:38:46
【问题描述】:

我必须使用 xlst 将 xml 转换为 html。如果不考虑命名空间声明,这相当简单。

因为我在找到这个处理命名空间的解决方案时遇到了一些麻烦,并且我很想知道是否可以以更简单的方式完成此操作。

我的问题是: 如何在声明时打印 xmlns,而不是在每个节点上。

给定以下 xml,命名空间应在声明时打印。根元素有两个命名空间声明,但调用

namespace::node()

列出所有命名空间。

<foo:root xmlns:foo="http://www.foo.com" xmlns:bar="http://www.bar.com">
    <xx:child xmlns:xx="http://www.xx.com" />
    <bar:otherChild>
        <defaultNamespace />
    </bar:otherChild>
</foo:root>

解决方案:

<!--
Select the current namespace without the xml namespace and without the namespaces of all ancestors (parents)
-->
<xsl:for-each select="namespace::node()[name()!='xml'][not(.=ancestor::*[position()&gt;1]/namespace::*)]">
  <xsl:variable name="name" select="name(current())" /> <!-- would be foo -->
  <xsl:variable name="namespace" select="current()" /> <!-- http://www.foo.com -->
</xsl:for-each>

【问题讨论】:

  • 您的问题不清楚(您的解决方案也不清楚)。您要达到的实际输出是什么?

标签: xml xslt xpath namespaces xslt-1.0


【解决方案1】:

我认为你正在寻找的表达是这样的......

<xsl:for-each select="namespace::node()[name()!='xml'][not(. = ../ancestor::*/namespace::node())]">

即如果当前节点的祖先上不存在命名空间,则写出该命名空间。

以这个 XSLT 为例

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

  <xsl:template match="*">
    <xsl:text>Node: </xsl:text><xsl:value-of select="local-name()" />
    <xsl:text>&#10;</xsl:text>
    <xsl:for-each select="namespace::node()[name()!='xml'][not(. = ../ancestor::*/namespace::node())]">
      <xsl:value-of select="name(current())" /> 
      <xsl:text> - </xsl:text>
      <xsl:value-of select="current()" />
      <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
    <xsl:text>&#10;</xsl:text>
    <xsl:apply-templates />
  </xsl:template>
</xsl:stylesheet>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多