0

我有一个 XML 文件:

<Picture id="001.png"/>

<Line/>

<Picture id="002.png"/>

<Line/>

<Picture id="003.png"/>

并想将其更改为:

<Picture id="001.png"/>

<Line/>

<Picture id="002.png"/>

我可以通过以下xsl删除“003.png”,因为我知道它的id,但不知道如何删除它上面的“Line”。

 <xsl:template
     match="//Picture[@id='003.png']">
 </xsl:template>

我可以通过跟随兄弟姐妹来做到这一点吗?多谢:)

4

2 回答 2

0

您的输入不是格式良好的 XML,因为它没有根元素,但这里有一个选项:

样式表

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
  <xsl:strip-space elements="*"/>

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

  <!--
  Drop unwanted elements: <Picture id="003.png"/> and the <Line/> element
  preceding it
  -->
  <xsl:template
    match="Line[following-sibling::*[1][self::Picture[@id = '003.png']]]
         | Picture[@id = '003.png']"/>
</xsl:stylesheet>

输入

<Elements>
  <Picture id="001.png"/>
  <Line/>
  <Picture id="002.png"/>
  <Line/>
  <Picture id="003.png"/>
</Elements>

输出

<Elements>
  <Picture id="001.png"/>
  <Line/>
  <Picture id="002.png"/>
</Elements>
于 2013-04-09T11:30:20.680 回答
0

是的,您可以使用以下兄弟姐妹来做到这一点。如下更改 Eero Helenius 的代码。

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
      <xsl:output method="xml" version="1.0" encoding="utf-8" indent="yes"/>
      <xsl:strip-space elements="*"/>

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

      <!--
      Drop unwanted elements: <Line> with fist following-sibling::Picture id = '003.png
      <Picture id="003.png"/>
      -->
      <xsl:template match="Picture[@id = '003.png']"/>

      <xsl:template match="Line">
          <xsl:if test="not(following-sibling::Picture[1][@id = '003.png'])">
            <xsl:copy>
              <xsl:apply-templates select="node() | @*"/>
            </xsl:copy>
        </xsl:if>
       </xsl:template>
    </xsl:stylesheet>
于 2013-04-09T15:42:27.097 回答