当 xml 具有与元素关联的命名空间时,如何使用 xslt 从 xml 正确获取数据

How to correctly fetch data from xml using xslt when xml has namespace associated with elements

我正在尝试使用 xslt 进行一些转换,但是如果在 XML 文件中声明名称空间,我将面临一些问题:

示例:

<?xml version="1.0" encoding="UTF-8"?>
 <rootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://example.com/ XSD.xsd"
   xmlns="http://example.com/">

  <elem1> TEST </elem1>

</rootNode>

在 xsl 样式表中,我有这样的代码:

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

<xsl:output omit-xml-declaration="no" indent="yes"/>

 <xsl:template match="/">

     <TAG1>  <xsl:value-of select="elem1"/> </TAG1>

 </xsl:template>

</xsl:stylesheet>

问题是,如果我不删除 XML 中的命名空间,即: xmlns="http://example.com/"

没有从 XML 文件中提取任何值。

我试着搜索了很多帖子,但是我没有得到任何关于正在发生的事情的具体线索。我想,不知何故,它可能与命名空间有关,我也试过,没有从 XML.

获取任何值

非常感谢这方面的任何帮助。

您只需在 XSLT 中声明名称空间即可。像这样的东西会起作用(注意 exclude-result-prefixes,它可以防止新的命名空间绑定作为输出的一部分弹出):

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:ex="http://example.com/"
    exclude-result-prefixes="ex">

    <xsl:output omit-xml-declaration="no" indent="yes"/>

     <xsl:template match="/">
         <TAG1>  <xsl:value-of select="ex:elem1"/> </TAG1>
     </xsl:template>

</xsl:stylesheet>

Remember that namespace prefixes are just placeholders for the actual namespace。因此,即使您在 XSLT 中将前缀绑定到名称空间,它在其他 XML 文档中也可能具有不同的前缀(或没有前缀),只要它绑定到相同的名称空间即可。

您的代码的另一个问题是您的主模板匹配根节点 /(在根元素 rootNode 之前)。因此,除了命名空间的修复之外,您还必须修复您的 XPath:

<xsl:value-of select="ex:rootNode/ex:elem1"/>