1

全部

我有以下格式的 XML

 <a>
<a1 id="1"/>
<a1 id="2"/>
<a1 id="3"/>
<a1 id="4"/>
<a1 id="5"/>
</a>

现在,使用 XSLT 我想删除前 2 个节点(基于它们的位置)并再次创建 XML。所以上面的输出应该遵循 XML:

<a>

    <a1 id="3"/>
    <a1 id="4"/>
    <a1 id="5"/>
    </a>

我用过的代码:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" />
  <xsl:template match="a1">
  &lt;a1&gt;
    <xsl:copy>
      <xsl:value-of select="@id"/>

    </xsl:copy>
&lt;/a1&gt;
  </xsl:template>
  <xsl:template match="a1[position()&lt;2]"></xsl:template>
</xsl:stylesheet>

但我得到的输出是

<a1> 2 </a1>
  <a1> 3 </a1>
  <a1> 4 </a1>
  <a1> 5 </a1>
4

2 回答 2

0

You can use something called the identity template to accomplish this very easily. That would be the first template in my example. All that says is process every attribute and node. After that all you have to do is not process any a1 node with a position less than 3 by using a blank template.

So using this XSLT

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

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

  <xsl:template match="a1[position()&lt;3]" />

</xsl:stylesheet>

On this XML

<a>
  <a1 id="1"/>
  <a1 id="2"/>
  <a1 id="3"/>
  <a1 id="4"/>
  <a1 id="5"/>
</a>

Produces this output

<a>


  <a1 id="3"/>
  <a1 id="4"/>
  <a1 id="5"/>
</a>
于 2013-09-17T21:07:18.727 回答
0

听起来你需要fn:position()在处理你的子元素时使用<a>

fn:position() :返回当前正在处理的节点的索引位置

示例://book[position()<=3] 结果:选择前三个 book 元素

http://www.w3schools.com/xpath/xpath_functions.asp

于 2013-09-17T20:18:54.410 回答