【问题标题】:Copying elements to a new namespace with xslt使用 xslt 将元素复制到新命名空间
【发布时间】:2017-10-02 20:54:23
【问题描述】:

我正在尝试更改我的 XML 文件的命名空间。我很接近,但根元素有一点问题。

XSLT:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:cd="http://schemas.datacontract.org/2004/07/CMachine" xmlns="http://schemas.datacontract.org/2004/07/CMachine.DataContracts" exclude-result-prefixes="cd">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
  <xsl:strip-space elements="*" />
  <!-- Identify transform -->
  <xsl:template match="@*|text()|comment()|processing-instruction()">
    <xsl:copy/>
  </xsl:template>
  <!-- Create a new element in the new namespace for all elements -->
  <xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>

输入:

<?xml version="1.0" encoding="utf-8"?>
<Inventory xmlns="http://schemas.datacontract.org/2004/07/CMachine" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <Schema>2018</Schema>
  <Machines>
    <Machine>
      <Price>120000</Price>
      <Properties i:nil="true" />
    </Machine>
  </Machines>
</Inventory>

输出:

<?xml version="1.0" encoding="utf-8"?>
<Inventory xmlns="http://schemas.datacontract.org/2004/07/CMachine.DataContracts">
  <Schema>2018</Schema>
  <Machines>
    <Machine>
      <Price>120000</Price>
      <Properties i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
    </Machine>
  </Machines>
</Inventory>

期望的输出:

<?xml version="1.0" encoding="utf-8"?>
<Inventory xmlns="http://schemas.datacontract.org/2004/07/CMachine.DataContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" >
  <Schema>2018</Schema>
  <Machines>
    <Machine>
      <Price>120000</Price>
      <Properties i:nil="true" />
    </Machine>
  </Machines>
</Inventory>

我需要进行哪些调整才能正确转换 XML 输入?

【问题讨论】:

    标签: xml xslt namespaces


    【解决方案1】:

    有多种方法可以将命名空间声明(此处为 xmlns:i)放置在实际未使用的元素上(以元素的名称或其任何属性的名称)。

    在 XSLT 2.0 中,您可以使用 xsl:namespace 指令。

      <xsl:template match="/*">
        <xsl:element name="{local-name()}">
          <xsl:namespace name="i" select="'http://www.w3.org/2001/XMLSchema-instance'"/>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
      </xsl:template>
    

    在这种特殊情况下,名称空间存在于源文档中,因此您可以复制它(这也适用于 XSLT 1.0):

      <xsl:template match="/*">
        <xsl:element name="{local-name()}">
          <xsl:copy-of select="namespace::i"/>
          <xsl:apply-templates select="@*|node()"/>
        </xsl:element>
      </xsl:template>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-24
      • 2014-02-19
      • 2011-02-10
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多