【问题标题】:How do I strip / add namespaces / prefixes in this XML / XSLT?如何在此 XML/XSLT 中去除/添加名称空间/前缀?
【发布时间】:2019-01-02 08:02:33
【问题描述】:

给定以下 XML:

<?xml version="1.0" encoding="utf-8"?>
<Store>
  <p1:Document xmlns:p1="urn:iso:std:iso:xyz">
    <p1:Class>
      Hello
      <p1:Type>
        Now
      </p1:Type>
    </p1:Class>
    <!-- more elements -->
  </p1:Document>
</Store>

我将如何编写 XSLT 以按以下方式转换 Document 元素:

<?xml version="1.0" encoding="utf-8"?>
<Store>
  <Document xmlns="urn:iso:std:iso:123>
    <Class>
      Hello
      <Type>
        Now
      </Type>
    </Class>
    <!-- more elements -->
  </Document>
</Store>

如您所见,我需要复制 Document 元素,但我需要剥离其所有命名空间声明和前缀,然后添加一个新的命名空间声明。

我将如何在 XSL 中完成此任务?

【问题讨论】:

  • @zx485 - 您可能知道答案的新问题! :)

标签: xml xslt


【解决方案1】:

解决方案是答案的变体,例如
"How to remove namespace prefix leaving namespace value (XSLT)?",并应用具有mode 属性的模板仅处理Document 元素的子元素。

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:p1="urn:iso:std:iso:xyz" version="1.0">
  <xsl:output indent="yes" method="xml" />
  <xsl:variable name="replacementNamespace" select="'urn:iso:std:iso:123'" />

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

  <!-- template to replace namespace -->
  <xsl:template match="*" mode="newNamespace">
    <xsl:element name="{local-name()}" namespace="{$replacementNamespace}">
      <xsl:apply-templates select="@*|node()" mode="newNamespace" />
    </xsl:element>
  </xsl:template>

  <!-- template to process Document element -->
  <xsl:template match="p1:Document">
    <xsl:apply-templates select="." mode="newNamespace" />
  </xsl:template>

</xsl:stylesheet>

如果您仍然在输出文档中获得不需要的命名空间,请按照答案"XSL: Avoid exporting namespace definitions to resulting XML documents" 中的说明,并将exclude-result-prefixes="ns0 ns1" 添加到您的xsl:stylesheet 元素中。这应该很容易摆脱一些不需要的命名空间。

如果这没有帮助,您需要创建一个包含所有相关方面的最小、完整和可验证示例的新问题.


下次至少尝试通过在此网站上搜索答案自行解决问题。

【讨论】:

  • 我正在尝试,但仍然遇到障碍。最新的路障问题:stackoverflow.com/questions/51524370/…
  • 在我的 xml 编辑器中运行良好,但是当我通过 Java XSLT 转换器运行它时,它的输出如下: 等...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多