我可以在XSL样式表中为每个创建的元素指定一个默认命名空间吗?

StackOverflow https://stackoverflow.com/questions/1404756

  •  05-07-2019
  •  | 
  •  

我使用.NET将XML从DataSet转换为 sitemap 格式。这就是我现在所处的位置。如您所见,我使用正确的命名空间创建根元素。我注意到,如果我创建子节点,它们都有一个空的xmls属性(<url xmlns="">...</url>),除非我在模板中创建元素时指定了命名空间。

这不是很干。有没有办法定义创建的alle元素的命名空间?

<xsl:template match="/">
    <!-- Root element has a namespace -->
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
        <xsl:apply-templates/>
    </urlset>
</xsl:template>

<xsl:template match="Document">
    <!-- Do it this way to prevent empty xmlns attribute on element -->
    <xsl:element name="url" namespace="http://www.sitemaps.org/schemas/sitemap/0.9">
        <!-- This element will get the empty xmlns attribute, unless I create it like the url element -->
        <location>
            <xsl:value-of select="Path" />
        </location>
        <!-- There are more elements to create here, do I have to specify the namespace each time? -->
    </xsl:element>
</xsl:template>

谢谢!

有帮助吗?

解决方案

在样式表的根目录中指定默认命名空间。

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

或者,在我看来,首选解决方案是在根上定义一个前缀,稍后将其用于您的元素:

<xsl:stylesheet version="1.0" xmlns:sm="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <sm:urlset>
            <xsl:apply-templates/>
        </sm:urlset>
    </xsl:template>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top