使用XSL根据XML条件添加命名空间

时间:2018-09-28 08:33:14

标签: xml xslt namespaces

我正在尝试根据条件将名称空间添加到xml。但条件不起作用。有人可以帮忙吗。

输入XML:

function require(msg) {
  console.log(msg);
  return {
    "Server": function(msg) {
      console.log(msg)
    }
  }
}

require("require message").Server("some message");
require("Calling only require");
require("Calling require with Server").Server("This is a chained call...");

输出XML:

                    <n0:MainTag xmlns:n0='http://abc123.com' xmlns:prx='urn:testing.com' xmlns:soap-env='http://schemas.xmlsoap.org/soap/envelope/'>
                    <header>M</header>
                    <Data>
                        <Child>623471568753</Child>

                    </Data>
                </n0:MainTag>

第二个输入: 输入XML:

                    <?xml version="1.0" encoding="UTF-8"?>
                <ns0:MainTag xmlns:ns0="http://xyz987.com">
                    <header>M</header>
                    <Data>
                        <Child>623471568753</Child>
                    </Data>
                </n0:MainTag>

输出XML:

                <n0:DifferentTag xmlns:n0='http://abc123.com' xmlns:prx='urn:testing.com' xmlns:soap-env='http://schemas.xmlsoap.org/soap/envelope/'>
                <header>M</header>
                <Datum>
                    <Child>Test123</Child>

                </Datum>
            </n0:DifferentTag>

XSL尝试过:

                <n0:DifferentTag xmlns:ns0="http://QWR.com">
                <header>M</header>
                <Datum>
                    <Child>Test123</Child>

                </Datum>
            </n0:DifferentTag>

条件:要检查源XML中的标签名称

1 个答案:

答案 0 :(得分:1)

问题在于,在输入XML中,MainTagDifferentTag都在“ http://abc123.com”中,但是您在XSLT中考虑了这一点,因此它试图与没有名称空间的标签匹配。

您需要在XSLT中声明前缀,然后在匹配项中使用该前缀。

还请注意,当一个XSLT可能与MainTag相匹配时,您的当前XSLT有两个模板。

尝试使用此XSLT:

DifferentTag

编辑:如果您真的不知道输入XML中的名称空间,请尝试使用此XSLT ...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:n0="http://abc123.com"
                              exclude-result-prefixes="n0">
<xsl:output encoding='UTF-8' indent='yes' method='xml'/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="n0:MainTag">
    <xsl:element name="ns0:{local-name()}" namespace="http://xyz987.com">
        <xsl:apply-templates select="@* | node()" />
    </xsl:element>
</xsl:template>

<xsl:template match="n0:DifferentTag">
    <xsl:element name="ns0:{local-name()}" namespace="http://QWR.com">
        <xsl:apply-templates select="@* | node()" />
    </xsl:element>
</xsl:template>

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