[英]Copying elements to a new namespace with xslt
我正在嘗試更改XML文件的名稱空間。 我已經接近了,但是root元素出現了一點問題。
XSLT:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:cd="http://schemas.datacontract.org/2004/07/CMachine" xmlns="http://schemas.datacontract.org/2004/07/CMachine.DataContracts" exclude-result-prefixes="cd">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:strip-space elements="*" />
<!-- Identify transform -->
<xsl:template match="@*|text()|comment()|processing-instruction()">
<xsl:copy/>
</xsl:template>
<!-- Create a new element in the new namespace for all elements -->
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
輸入:
<?xml version="1.0" encoding="utf-8"?>
<Inventory xmlns="http://schemas.datacontract.org/2004/07/CMachine" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Schema>2018</Schema>
<Machines>
<Machine>
<Price>120000</Price>
<Properties i:nil="true" />
</Machine>
</Machines>
</Inventory>
輸出:
<?xml version="1.0" encoding="utf-8"?>
<Inventory xmlns="http://schemas.datacontract.org/2004/07/CMachine.DataContracts">
<Schema>2018</Schema>
<Machines>
<Machine>
<Price>120000</Price>
<Properties i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
</Machine>
</Machines>
</Inventory>
所需的輸出:
<?xml version="1.0" encoding="utf-8"?>
<Inventory xmlns="http://schemas.datacontract.org/2004/07/CMachine.DataContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" >
<Schema>2018</Schema>
<Machines>
<Machine>
<Price>120000</Price>
<Properties i:nil="true" />
</Machine>
</Machines>
</Inventory>
我需要做哪些調整才能正確地轉換XML輸入?
有幾種方法可以將名稱空間聲明(此處為xmlns:i
)放置在實際上未被使用的元素上(以元素名稱或其任何屬性)。
在XSLT 2.0中,可以使用xsl:namespace指令。
<xsl:template match="/*">
<xsl:element name="{local-name()}">
<xsl:namespace name="i" select="'http://www.w3.org/2001/XMLSchema-instance'"/>
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
在這種特殊情況下,源文檔中存在名稱空間,因此您可以跨名稱復制它(在XSLT 1.0中也可以使用):
<xsl:template match="/*">
<xsl:element name="{local-name()}">
<xsl:copy-of select="namespace::i"/>
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.