如何使用xslt复制前面的节点?

时间:2013-02-18 05:15:53

标签: xml xslt

我是XSLT的新手。我想复制一个特定节点的所有前面的节点,我试过复制和前面的,但输出不是我所期望的..

源示例XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
   <MetaData>
      <Owner>adad</Owner>
      <date>2013-1-12</date>
   </MetaData>
   <Orders>
      <Order name="123">
         <OrderName>Order1</OrderName>
         <OrderNo>1</OrderNo>
      </Order>
      <Order name="1234">
         <OrderName>Order2</OrderName>
         <OrderNo>2</OrderNo>
      </Order>
      <Order>
         <OrderName>Order3</OrderName>
         <OrderNo>3</OrderNo>
      </Order>
   </Orders>
   <tail>1111</tail>
</root>

XSL:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">

<xsl:output method="xml" indent="yes"/>

<xsl:template match = "Orders" name="split">
    <xsl:for-each select="Order">
    <xsl:if test="position() = 2">
        <xsl:copy-of select="preceding::node()"/>
        <xsl:copy-of select="."/>
    </xsl:if>
    </xsl:for-each>
</xsl:template> 
</xsl:stylesheet>

输出:

<?xml version="1.0" encoding="UTF-8"?>

      adad
      2013-1-12


   <MetaData>
      <Owner>adad</Owner>
      <date>2013-1-12</date>
   </MetaData>
      <Owner>adad</Owner>adad
      <date>2013-1-12</date>2013-1-12


      <Order name="123">
         <OrderName>Order1</OrderName>
         <OrderNo>1</OrderNo>
      </Order>
         <OrderName>Order1</OrderName>Order1
         <OrderNo>1</OrderNo>1

      <Order name="1234">
         <OrderName>Order2</OrderName>
         <OrderNo>2</OrderNo>
      </Order>
   1111

预期的XML:

<?xml version="1.0" encoding="UTF-8"?>
    <root>
       <MetaData>
          <Owner>adad</Owner>
          <date>2013-1-12</date>
       </MetaData>
       <Orders>
          <Order name="123">
             <OrderName>Order1</OrderName>
             <OrderNo>1</OrderNo>
          </Order>
          <Order name="1234">
             <OrderName>Order2</OrderName>
             <OrderNo>2</OrderNo>
          </Order>
        <Orders>
   </root>

看起来像<MetaData><Order>的后代被复制了三次.. 为什么<tail>节点丢失了元素名称?

有人可以帮我吗?感谢

1 个答案:

答案 0 :(得分:0)

如果要复制前两个节点,为什么不在for-each中明确选择它们,例如。 select="Order[position()<=2]

更新:这将选择所有元素,包括第二个Order元素:

select="*[count(preceding-sibling::Order) &lt; 2]