Xsl,Xpath跟随兄弟姐妹foreach

时间:2016-09-02 12:09:25

标签: xml xslt xpath

我想用XSL创建以下结构:

<div class="helloclass">C
<div class="hellomethod"><p>test</p></div>
<div class="hellomethod"><p>test</p></div>
</div>
<div class="helloclass">
</div>

我有以下XML:

<?xml version="1.0"?>
    <hello id="C"></hello>
    <hello id="M"></hello>
    <hello id="M"></hello>
    <hello id="C"></hello>
</xml>

使用XSL和Xpath我尝试了以下内容:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:foo="http://www.foo.org/" xmlns:bar="http://www.bar.org">
  <xsl:template match="/">
    <xsl:for-each select="hello">
      <xsl:if test="current()[contains(@id,'C')]">
        <xsl:for-each select="following-sibling">
          <xsl:if test="current()[contains@id,'M']">
            <p>Test</p>
          </xsl:if> 
         </xsl:for-each>
       </xsl:if>
    </xsl:for-each>
</xsl:template>
</xsl:styleshet>

我有一个扁平的xml结构。对于这个xml,我想根据id的结构创建。

ID =&#34; C&#34;意味着它应该被转换为&lt; div class =&#34; helloclass&#34; &GT; ID =&#34; M&#34;意味着它应该被转换为&lt; div class =&#34; hellomethod&#34; &GT;

我的第一个目标是显示文字:&#34; test&#34;在正确的节点中。

M也应该嵌套在C中,而不是xml中的兄弟。

以下序列也可能出现: CMMCCMMMC,或CCCCCCCCCCMM,或CM,......基本上我需要一个&#34;泛型&#34;溶液

仅限XLST 1.0处理器。

1 个答案:

答案 0 :(得分:0)

虽然这在XSLT 2.0中是一项微不足道的任务,但如果它是由XSLT 1.0处理器执行则远非微不足道。

请考虑以下事项:

<强> XML

<root>
    <hello id="C">A</hello>
    <hello id="M"></hello>
    <hello id="M"></hello>
    <hello id="C">B</hello>
    <hello id="C">C</hello>
    <hello id="M"></hello>
    <hello id="M"></hello>
    <hello id="M"></hello>
    <hello id="C">D</hello>
    <hello id="C">E</hello>
</root>

XSLT 1.0

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

<xsl:key name="method" match="hello[@id='M']" use="generate-id(preceding-sibling::hello[@id='C'][1])" />

<xsl:template match="/root">
    <body>
        <xsl:for-each select="hello[@id='C']">
            <div class="helloclass">
                <xsl:value-of select="."/>
                <xsl:for-each select="key('method', generate-id())">
                    <div class="hellomethod">
                        <p>test</p>
                    </div>
                </xsl:for-each>
            </div>
        </xsl:for-each>
    </body>
</xsl:template>

</xsl:stylesheet>

<强>结果

<body>
   <div class="helloclass">A
      <div class="hellomethod">
         <p>test</p>
      </div>
      <div class="hellomethod">
         <p>test</p>
      </div>
   </div>
   <div class="helloclass">B</div>
   <div class="helloclass">C
      <div class="hellomethod">
         <p>test</p>
      </div>
      <div class="hellomethod">
         <p>test</p>
      </div>
      <div class="hellomethod">
         <p>test</p>
      </div>
   </div>
   <div class="helloclass">D</div>
   <div class="helloclass">E</div>
</body>