【问题标题】:XSLT Namespace Unable to read ns0:XSLT 命名空间无法读取 ns0:
【发布时间】:2025-12-21 11:55:06
【问题描述】:

我是 XML 和 XSLT 转换的新手。我创建了一个 XSLT 文件,它可以正确翻译客户提供的 XML 文件,但只有在我删除 ns0 行时才会这样做 - 因为我无法控制收到的文件我需要能够读取文件在保留 ns0 行的情况下,我查看了几个似乎与同一问题相关的已回答问题,但我是一个新手,我很难理解答案如何适用于我的问题,详细信息如下:-

XML 文件以

开头
<?xml version="1.0" encoding="UTF-8"?>

<ns0:MyRecord xmlns:ns0="https://some/kind/of/text">

并以 ns0:MyRecord 结尾

我已经编写了一个 XSLT(如下所示)来转换 XML,它只有在我删除

<?xml version="1.0" encoding="utf-8"?>

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

<xsl:output method="xml" indent="yes"/>
<xsl:template match="/">

<ImportJobs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <description>Jobs Import Test</description>
  <copyright>© A Software Company Ltd 2015</copyright>
  <Exceptions></Exceptions>
  <DataItems>
    <xsl:for-each select="MyRecord/ImportJobs/DataItems/Job">
      <Job>
        <CustomerAlpha>
          <xsl:text>AnAccountNo</xsl:text>
        </CustomerAlpha>
        <SiteAlpha>
          <xsl:text></xsl:text>
        </SiteAlpha>
        <EquipNo>
          <xsl:text></xsl:text>
        </EquipNo>
        <Authority>
          <xsl:text></xsl:text>
        </Authority>
        <Reference>
          <xsl:text></xsl:text>
        </Reference>
    <UserRef2>
          <xsl:value-of select="JobNumber"/>
        </UserRef2>
    </xsl:for-each>
  </DataItems>

</ImportJobs>

</xsl:template>
</xsl:stylesheet>

我认为我应该添加 xmlns:ns0="https://some/kind/of/text" 但即使我这样做也不允许 XSLT 查看数据

无论我尝试什么,我都会得到

<?xml version="1.0" encoding="utf-8"?>
<ImportJobs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <description>Jobs Import Test</description>
  <copyright>© A Software Company Ltd 2015</copyright>
  <Exceptions />
  <DataItems />
</ImportJobs>

【问题讨论】:

  • 上面的文字应该说“只有当我从它正在寻求处理的提供的 XML 中删除 ns0 行时它才有效
  • 最好edit您的问题,而不是仅仅添加评论(可以删除,反正不太明显)。

标签: xml xslt xml-namespaces


【解决方案1】:

您的指示:

<xsl:for-each select="MyRecord/ImportJobs/DataItems/Job">

不选择任何内容,因为MyRecord 元素位于命名空间中。为了选择它,您需要在样式表中声明相同的命名空间,为其分配一个前缀并在 select 表达式中使用该前缀 - 例如:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ns0="https://some/kind/of/text"
exclude-result-prefixes="ns0">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="/">
    <ImportJobs xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <!-- ... -->
        <DataItems>
            <xsl:for-each select="ns0:MyRecord/ImportJobs/DataItems/Job">
                <!-- ... -->
            </xsl:for-each>
        </DataItems>
    </ImportJobs>
</xsl:template>

</xsl:stylesheet>

这是假设后代节点 - ImportJobsDataItemsJob - 不在命名空间中 - 否则它们也需要前缀。

【讨论】:

  • 非常感谢 Michael.hor257k 你解决了我的问题