how to remove namespace and prefix attibutes from

2019-08-05 12:45发布

i have an xml as follows

<Publication xmlns:n1="http://www.w3.org/2001/XMLSchema-instance" n1:noNamespaceSchemaLocation="InformaKMSStructure.xsd"

i want copy all XML but not xmlns:n1="http://www.w3.org/2001/XMLSchema-instance" and n1:noNamespaceSchemaLocation="InformaKMSStructure.xsd"

标签: xml xslt
2条回答
Explosion°爆炸
2楼-- · 2019-08-05 13:39

n1:noNamespaceSchemaLocation="InformaKMSStructure.xsd" is an ordinary attribute, and the way to "remove" it in XSLT is to refrain from copying it. If you don't do anything in XSLT, you don't produce any output, so if you want to avoid outputting something then you need to find the code that's outputting it and change it. You haven't shown us your code so we can't tell you how to change it.

xmlns:n1="http://www.w3.org/2001/XMLSchema-instance" is different: in the XPath data model it's not treated as an attribute, but as a namespace. In fact, the presence of this namespace declaration causes a namespace node to be present on every element within its scope. To get rid of these namespaces, you need to understand which instructions copy namespaces and which don't. In XSLT 1.0, xsl:copy and xsl:copy-of, when applied to an element, copy all the element's namespaces (whether declared on that element or on an ancestor). To stop this happening, in XSLT 2.0 you can use <xsl:copy copy-namespaces="no">, but in 1.0 the only option is to reconstruct the element using xsl:element rather than xsl:copy.

查看更多
倾城 Initia
3楼-- · 2019-08-05 13:42

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

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

 <xsl:template match="node()[not(self::*)]|@*">
  <xsl:copy/>
 </xsl:template>

 <xsl:template match=
 "@*[namespace-uri() = 'http://www.w3.org/2001/XMLSchema-instance']"/>
</xsl:stylesheet>

when applied on the following XML document (none provided!):

<Publication
 xmlns:n1="http://www.w3.org/2001/XMLSchema-instance"
 n1:noNamespaceSchemaLocation="InformaKMSStructure.xsd">
  <a x="y">
   <b/>
  </a>

  <c/>
</Publication>

produces the wanted, correct result:

<Publication>
   <a x="y">
      <b/>
   </a>
   <c/>
</Publication>

Explanation:

This follows the usual pattern of overriding the identity rule, however the identity rule is replaced by two templates -- one matching any element anf the second matching any other node or attribute.

查看更多
登录 后发表回答