0

我是 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>节点丢失了元素名称?

谁能帮我解决这个问题?谢谢

4

1 回答 1

0

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

更新:这将选择直到并包括第二个 Order 元素的所有元素:

select="*[count(preceding-sibling::Order) &lt; 2]
于 2013-02-18T05:48:38.563 回答