2014-04-22 143 views
1

我有一個xml文檔,需要用包含節點和處理指令的部分xml段替換特定節點。我想保留PI,但遇到更換問題。XSLT使用處理指令將部分XML段導入XML

段例如:general.xml

<root> 
    <!--General Settings --> 
    <?mapping EnvironmentSetting="envname"?> 
    <setting name="SubscriptionName" value="*" /> 
</root> 

源XML:

<environment> 
    <General /> 
</environment> 

變換 -

<xsl:template match="* | processing-instruction() | comment()"> 
    <xsl:copy> 
    <xsl:copy-of select="@*"/> 
    <xsl:apply-templates/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="*/General"> 
    <xsl:copy-of select="document('general.xml')/root"/> 
</xsl:template> 

的輸出是:

<environment> 
    <root> 
    <!--General Settings --> 
    <?mapping EnvironmentSetting="envname"?> 
    <setting name="SubscriptionName" value="*" /> 
    </root> 
</environment> 

但我想:

<environment> 
    <!--General Settings --> 
    <?mapping EnvironmentSetting="envname"?> 
    <setting name="SubscriptionName" value="*" /> 
</environment> 

更改文檔部分到根/ *下降處理的指令(和註釋)

<xsl:copy-of select="document('general.xml')/root/*"/> 
... 
<environment> 
    <setting name="SubscriptionName" value="*" /> 
</environment> 

更改文檔部分到根/過程的指令丟棄節點

<xsl:copy-of select="document('general.xml')/root/processing-instruction()"/> 
... 
<environment> 
    <?mapping EnvironmentSetting="envname"?> 
</environment> 

正在嘗試做|只是比賽的第一個參數 -

<xsl:copy-of select="document('general.xml')/root/processing-instruction() | * | comment()"/> 
... 
<environment> 
    <?mapping EnvironmentSetting="envname"?> 
</environment> 

那麼,如何讓我的魚與熊掌兼得呢?我看起來如此接近,但在找到我想做的事情的例子時遇到問題。

+0

修改後的身份模板是相當奇怪的。從實際的身份模板開始,爲不希望複製的節點類型添加空模板會更有用。 '的 Tomalak

+0

不知道我理解你的意見,你的你指的身份模板,該模板部分我是相當新的XSLT? ,所以請原諒我的無知,如果這似乎是我問一個愚蠢的問題。 – James

+0

我指的是第一個''你的問題。恆等變換(又名身份模板)是XSLT真正的基本功能之一,你會僅靠這些關鍵字找到噸的閱讀材料。 – Tomalak

回答

0

這應做到:

<xsl:template match="* | processing-instruction() | comment()"> 
    <xsl:copy> 
    <xsl:copy-of select="@*"/> 
    <xsl:apply-templates/> 
    </xsl:copy> 
</xsl:template> 

<xsl:template match="*/General"> 
    <xsl:apply-templates select="document('general.xml')/root"/> 
</xsl:template> 

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

或者你可以把幾種類型的使用union運算節點的副本:

<xsl:template match="*/General"> 
    <xsl:variable name="r" select="document('general.xml')/root" /> 
    <xsl:apply-templates select="$r/* | $r/processing-instruction() | $r/comment()" /> 
</xsl:template> 
+0

第一個例子是我需要什麼。我其實有多個文檔片段,並取決於我想作爲輸出XML,我需要抓住一個或多個這些片段。 我你會更多地關注你的第二個擴展我所做事情的例子,還沒有使用變量 – James

+0

順便說一句:定義你需要多次的變量是有意義的在頂層而不是在單獨的模板中。 – Tomalak