XSLT - Ignore/Remove the empty namespace in the ch

2019-07-28 05:59发布

In order to be able to be able to have a root element with a dynamic namespace value I switched it from: <Foo xmlns="HardCodedXMLNS"> to: <xsl:element name="Foo" namespace="{Table/Foo_Dynamic_XMLNS}">

The current XSLT looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="xml" />
    <xsl:template match="/NewDataSet">
        <xsl:element name="Foo" namespace="{Table/Foo_xmlns}">
            <Bar Id ="{Table/Bar_Id}">
            </Bar>
        </xsl:element>
    </xsl:template>
</xsl:stylesheet>

Now the problem is that the <Bar> element gets an empty namespace after transformation like this (Current output):

<Foo xmlns="http://MyDynamicValue">
    <Bar xmlns="">
    </Bar>
</Foo>

Expected output:

<Foo xmlns="http://MyDynamicValue">
    <Bar>
    </Bar>
</Foo>

Question: How would one solve this problem so that the Bar node doesn't have the namespace?

标签: xml xslt
2条回答
手持菜刀,她持情操
2楼-- · 2019-07-28 06:15

Both of your elements have different namespace values. Without using namespace prefixes, the xmlns namespace binding attribute is required in order to express what the namespace value is for those elements.

The element named root is bound to the namespace MyNS and the element named child is in the "no namespace" and has none.

Since the parent element is bound to a namespace and does not use a namespace-prefix, it's child element - which has no namespace, will have the empty namespace declaration. The xmlns namespace declaration attribute is present to indicate what the namespace is (or to indicate that it has none).

Otherwise, if your XML was:

<root xmlns="MyNS">
  <child />
</root>

then the child element would be bound to the "MyNS" namespace. It would be the equivalent of:

<m:root xmlns:m="MyNS">
  <m:child/>
</m:root>

If the element named root had a namespace prefix, then you could have the output, in which the element named root is bound to the MyNS namespace and the element named child has no namespace and does not need the empty namespace declaration xmlns="":

<m:root xmlns:m="MyNS">
  <child/>
</m:root>
查看更多
叼着烟拽天下
3楼-- · 2019-07-28 06:37

Generally, the principle is: if you put the elements in the right namespace, the namespace declarations will look after themselves. The reason you have an xmlns="" declaration on the child is that you created the child element as a no-namespace element.

(If you want actual code in the answer, then put some code in the question. In particular, your title talks about setting the namespace dynamically, but you haven't explained whether it really needs to be dynamic).

查看更多
登录 后发表回答