簡體   English   中英

如何使用xslt從源xml中刪除命名空間和前綴attibutes?

[英]how to remove namespace and prefix attibutes from a source xml using xslt?

我有一個xml如下

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

我想要復制所有XML而不是xmlns:n1 =“http://www.w3.org/2001/XMLSchema-instance”和n1:noNamespaceSchemaLocation =“InformaKMSStructure.xsd”

這種轉變

<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>

當應用於以下XML文檔時 (沒有提供!):

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

  <c/>
</Publication>

產生想要的,正確的結果:

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

說明

這遵循通常的覆蓋身份規則的模式,但是身份規則被兩個模板替換 - 一個匹配任何元素,第二個匹配任何其他節點或屬性。

n1:noNamespaceSchemaLocation =“InformaKMSStructure.xsd”是一個普通的屬性,在XSLT中“刪除”它的方法是避免復制它。 如果你在XSLT中沒有做任何事情,你就不會產生任何輸出,所以如果你想避免輸出某些內容,那么你需要找到輸出它的代碼並進行更改。 您尚未向我們展示您的代碼,因此我們無法告訴您如何更改它。

xmlns:n1 =“http://www.w3.org/2001/XMLSchema-instance”不同:在XPath數據模型中,它不被視為屬性,而是作為命名空間。 實際上,此命名空間聲明的存在會導致命名空間節點出現在其范圍內的每個元素上。 要擺脫這些名稱空間,您需要了解哪些指令復制名稱空間,哪些不復制名稱空間。 在XSLT 1.0中,xsl:copy和xsl:copy-of,當應用於元素時,復制所有元素的命名空間(無論是在該元素上還是在祖先上聲明的)。 為了阻止這種情況發生,在XSLT 2.0中你可以使用<xsl:copy copy-namespaces="no"> ,但在1.0中,唯一的選擇是使用xsl:element而不是xsl:copy重建元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM