Selecting every node and siblings (until next occu

2019-05-22 04:09发布

I have the following html structure:

<document>
<ol>a question</ol>
<div>answer</div>
<div>answer</div>
<ol>another question</ol>
<div>answer</div>
<ol>question #3</ol>
...
</document>

I would like to take the <ol> nodes and the following <div> nodes until the next <ol> node, so I can group them in an xml like

<vce>
  <topic>
   <question> ... </question>
   <answer> ... </answer>
  </topic>
  ...
</vce>

So far I have the following

<xsl:for-each select="//body/ol">
  <document>

    <content name="question">
      <xsl:value-of select="." />
    </content>

    <content name="answer">
      <xsl:for-each
        select="./following-sibling::div !!! need code here !!!>
        <xsl:value-of select="." />
      </xsl:for-each>
    </content>
  </document>
</xsl:for-each>

I get the questions just fine but I'm having trouble with the answers. I have tried working with following, preceding, not, for-each-group, ... . There are many similar questions but not quit like this with this format because I don't really have a child-parent structure in my html file.

标签: xslt xpath
1条回答
啃猪蹄的小仙女
2楼-- · 2019-05-22 04:25

Try it this way:

XSLT 1.0

<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:key name="answers" match="div" use="generate-id(preceding-sibling::ol[1])" />

<xsl:template match="/document">
    <vce>
        <xsl:for-each select="ol">
            <topic>
                <question>
                    <xsl:value-of select="." />
                </question>
                <xsl:for-each select="key('answers', generate-id())">
                    <answer>
                        <xsl:value-of select="." />
                    </answer>
                </xsl:for-each>
            </topic>
        </xsl:for-each>
    </vce>
</xsl:template>

</xsl:stylesheet>

when applied to the following test input:

XML

<document>
   <ol>question A</ol>
   <div>answer A1</div>
   <div>answer A2</div>
   <ol>question B</ol>
   <div>answer B1</div>
   <ol>question C</ol>
   <div>answer C1</div>
   <div>answer C2</div>
</document>

the result will be:

<?xml version="1.0" encoding="UTF-8"?>
<vce>
   <topic>
      <question>question A</question>
      <answer>answer A1</answer>
      <answer>answer A2</answer>
   </topic>
   <topic>
      <question>question B</question>
      <answer>answer B1</answer>
   </topic>
   <topic>
      <question>question C</question>
      <answer>answer C1</answer>
      <answer>answer C2</answer>
   </topic>
</vce>
查看更多
登录 后发表回答