2013-04-04 47 views
0

我有一个相当复杂的XML结构,但在一小段中,我在下面的结构中列出了输入/输出时间以及它可能包含的潜在数据:如何根据您在层次结构中的位置找到XML元素

<EventSummary> 
    <Name>In/Out times</Name> 
    <Entries> 
     <Entry> 
     <Name>In</Name> 
     <Time>4/1/2013 10:45</Time> 
     <Value>1</Value> 
     </Entry> 
     <Entry> 
     <Name>In</Name> 
     <Time>4/1/2013 10:55</Time> 
     <Value>1</Value> 
     </Entry> 
     <Entry> 
     <Name>Out</Name> 
     <Time>4/1/2013 11:30</Time> 
     <Value>0</Value> 
     </Entry> 
     <Entry> 
     <Name>In</Name> 
     <Time>4/1/2013 11:35</Time> 
     <Value>1</Value> 
     </Entry> 
    </Entries> 
</EventSummary> 

因此,条目保证按时间顺序排列,但我需要协调一个时间与下一个时间。因此,在上面的示例中,我们有一个时间,其次是另一个时间,然后是时间。我需要的最终产品的样子,在这种情况下是这样的:

<Table> 
    <Row> 
    <Cell> 
     <Text>4/1/2013 10:45</Text> 
    </Cell> 
    <Cell> 
     <Text>4/1/2013 11:30</Text> 
    </Cell> 
    </Row> 
    <Row> 
    <Cell> 
     <Text>4/1/2013 11:35</Text> 
    </Cell> 
    </Row> 
</Table> 

基本上我需要输入/输出对每个一行。所以我需要找到第一个In,然后跳过所有下一个Ins,直到第一个Out,然后如果在Out之后找到另一个In,则开始新行......等等。

我只是无法弄清楚如何在循环查找入口时查找入口或出口。有任何想法吗?

回答

1

这应做到:

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

    <xsl:template match="/"> 
    <Table> 
     <xsl:apply-templates 
     select="EventSummary/Entries 
        /Entry[Name = 'In' and 
          (not(preceding-sibling::Entry) or 
          preceding-sibling::Entry[1]/Name = 'Out')]" /> 
    </Table> 
    </xsl:template> 

    <xsl:template match="Entry[Name = 'In']"> 
    <Row> 
     <xsl:apply-templates 
     select="Time | 
       following-sibling::Entry[Name = 'Out'][1]/Time" /> 
    </Row> 
    </xsl:template> 

    <xsl:template match="Time"> 
    <Cell> 
     <Text> 
     <xsl:value-of select="." /> 
     </Text> 
    </Cell> 
    </xsl:template> 
</xsl:stylesheet> 

当你的样品输入运行,其结果是:

<Table> 
    <Row> 
    <Cell> 
     <Text>4/1/2013 10:45</Text> 
    </Cell> 
    <Cell> 
     <Text>4/1/2013 11:30</Text> 
    </Cell> 
    </Row> 
    <Row> 
    <Cell> 
     <Text>4/1/2013 11:35</Text> 
    </Cell> 
    </Row> 
</Table> 
相关问题