【问题标题】:XML element reordering not working XSLTXML 元素重新排序不起作用 XSLT
【发布时间】:2016-06-14 00:35:36
【问题描述】:

我正在尝试使用 XSLT 1.0 重新排序 XML 中的元素。下面是 XML 的小 sn-p

<RIMSDB1 xmlns="http://kiris.nps21.org/xsd">
    <ROW>
        <ReportID>1</ReportID>
        <WKYMD>20160610</WKYMD>
        <RunSystemDate>20160610032048</RunSystemDate>
    </ROW>
    <ROW>
        <ReportID>2</ReportID>
        <WKYMD>27869</WKYMD>
        <RunSystemDate>495876043985778649</RunSystemDate>
    </ROW>

这是我用来转换它的 XSLT。

<xsl:template match="*/ROW">
<xsl:copy>
    <xsl:apply-templates select="@*" />
    <xsl:apply-templates select="WKYMD" />
    <xsl:apply-templates select="RunSystemDate" />
    <xsl:apply-templates select="ReportID" />
</xsl:copy>

问题是当我转换时,我的顺序没有变化,但我从

中删除了 xmlns="http://kiris.nps21.org/xsd"
<RIMSDB1 xmlns="http://kiris.nps21.org/xsd">

我得到正确的转换,即:

<RIMSDB1>

    <ROW>
    <WKYMD>20160610</WKYMD>
    <RunSystemDate>20160610032048</RunSystemDate>
    <ReportID>1</ReportID>
</ROW>
    <ROW>
    <WKYMD>27869</WKYMD>
    <RunSystemDate>495876043985778649</RunSystemDate>
    <ReportID>2</ReportID>
</ROW>

如果有更好的重新排序方法,任何人都可以了解正在发生的事情吗?

提前致谢。

【问题讨论】:

    标签: c# xml xslt xslt-1.0


    【解决方案1】:

    当您的源文档包含xmlns="http://kiris.nps21.org/xsd" 时,您的所有元素(没有命名空间前缀或覆盖命名空间声明)将继承该命名空间并绑定到命名空间http://kiris.nps21.org/xsd。当没有命名空间前缀时,有时很难注意到或理解。

    您应该调整您的 XSLT 以使用前缀声明该命名空间,然后调整选择和匹配表达式以使用命名空间前缀以正确处理这些元素。

    例如:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
        xmlns:k="http://kiris.nps21.org/xsd"
        version="1.0">
        <xsl:template match="*/k:ROW">
            <xsl:copy>
                <xsl:apply-templates select="@*" />
                <xsl:apply-templates select="k:WKYMD" />
                <xsl:apply-templates select="k:RunSystemDate" />
                <xsl:apply-templates select="k:ReportID" />
            </xsl:copy>
        </xsl:template>
    </xsl:stylesheet>
    

    【讨论】:

    • @Mads-这对我有用,但我遇到了其他问题。如何在父标签和子标签中使用命名空间来处理这个问题,例如&lt;RIMSDB1 xmlns="http://kiris.nps21.org/xsd"&gt; &lt;EDDP_CSI_ADJPORTINVEST_HSTY xmlns=""&gt; &lt;ROW&gt; &lt;ReportID&gt;1&lt;/ReportID&gt; &lt;WKYMD&gt;20160610&lt;/WKYMD&gt; &lt;RunSystemDate&gt;20160610032048&lt;/RunSystemDate&gt; &lt;/ROW&gt; &lt;ROW&gt; &lt;ReportID&gt;2&lt;/ReportID&gt; &lt;WKYMD&gt;27869&lt;/WKYMD&gt; &lt;RunSystemDate&gt;495876043985778649&lt;/RunSystemDate&gt; &lt;/ROW&gt; &lt;/EDDP_CSI_ADJPORTINVEST_HSTY&gt; &lt;/RIMSDB1&gt;
    • 在该示例中,带有 xmlns="" 的元素被放置在“无命名空间”中,现在它及其后代不在文档元素中声明的命名空间中。对于“无命名空间”中的那些,您不要在选择/匹配表达式中使用命名空间前缀。
    • 如果您的输入不是标准的,并且您不确定元素将绑定到的时间/哪个命名空间,您可以使用更通用的匹配表达式,它只关心 local-name() 和不关心命名空间uri()。例如 *[local-name()='WKYMD']
    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多