2010-08-08 21 views
1

我有一個XML文件:如何使用xslt和xsltproc向xml添加零件?

<?xml version="1.0" encoding="iso-8859-1"?> 
<Configuration> 
    <Parameter2> 
    </Parameter2> 
</Configuration> 

,我想補充以下部分<Configuration><Parameter2>部分之間我的XML文件。

<Parameter1> 
    <send>0</send> 
    <interval>0</interval> 
    <speed>200</speed> 
</Parameter1> 

回答

0

較短的解決方案。這個樣式表:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:template match="@*|node()" name="identity"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()" /> 
     </xsl:copy> 
    </xsl:template> 
    <xsl:template match="Configuration/*[1]"> 
     <Parameter1> 
      <send>0</send> 
      <interval>0</interval> 
      <speed>200</speed> 
     </Parameter1> 
     <xsl:call-template name="identity" /> 
    </xsl:template> 
</xsl:stylesheet> 

輸出:

<Configuration> 
    <Parameter1> 
     <send>0</send> 
     <interval>0</interval> 
     <speed>200</speed> 
    </Parameter1> 
    <Parameter2></Parameter2> 
</Configuration> 

注意:如果你想添加Parameter1僅如果沒有在任何位置這樣的元素,你應該改變的模式:Configuration/*[1][not(/Configuration/Parameter1)]

3

這XSLT插入指定的內容作爲Configuration元素的子元素,Parameter2之前。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output indent="yes" /> 

    <xsl:template match="Configuration"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*" /> 
      <!--Check for the presence of Parameter1 in the config file to ensure that it does not get re-inserted if this XSLT is executed against the output--> 
      <xsl:if test="not(Parameter1)"> 
       <Parameter1> 
        <send>0</send> 
        <interval>0</interval> 
        <speed>200</speed> 
       </Parameter1> 
      </xsl:if> 
      <!--apply templates to children, which will copy forward Parameter2 (and Parameter1, if it already exists)--> 
      <xsl:apply-templates select="node()" /> 
     </xsl:copy> 
    </xsl:template> 

    <!--standard identity template, which copies all content forward--> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()" /> 
     </xsl:copy> 
    </xsl:template> 

</xsl:stylesheet> 
+0

我想我會使用副本,而不是遞歸模板爲孩子做副本,但是,這應該這樣做。如果我可以對現有Parameter1進行防禦,我會投兩次票。 – 2010-08-08 19:31:06