使用XSLT将基于子元素值的多个元素组合在一起

时间:2016-11-10 20:44:25

标签: xml xslt

好的XSLT显然超出了我的范围,我需要一些帮助。我还没有能够将存在的多个堆栈溢出帖子放在一个连贯的,工作的代码段中。 我有一个XML文件,有多个这样的条目

<?xml version="1.0" encoding="utf-8"?>
    <events>
      <event>
        <EventType>Blah</EventType>
        <title>Blah Blah</title>
        <RelatedLocations>Blah</RelatedLocations>
        <Date>Friday, September 2, 2016</Date>
        <DateYear>2016</DateYear>
        <DateMonth>09</DateMonth>
        <DateDay>02</DateDay>
        <Body>Derp</Body>
        <Notes>Notes are not displayed to the public.</Notes>
      </event>
      <event>
        <EventType>Blah</EventType>
        <title>Blah Blah</title>
        <RelatedLocations>Blah</RelatedLocations>
        <Date>Friday, October 7, 2016</Date>
        <DateYear>2016</DateYear>
        <DateMonth>09</DateMonth>
        <DateDay>07</DateDay>
        <Body>Derp</Body>
        <Notes>Notes are not displayed to the public.</Notes>
      </event>
    </events>

我想将它们组合在一起,根据标题相同而且相关地点是相同的,以便它们像这样阅读

<event>
        <EventType>Blah</EventType>
        <title>Blah Blah</title>
        <RelatedLocations>Blah</RelatedLocations>
        <Date>Friday, September 2, 2016, Friday, October 7, 2016</Date>
        <DateYear>2016</DateYear>
        <DateMonth>09</DateMonth>
        <DateDay>07</DateDay>
        <Body>Derp</Body>
        <Notes>Notes are not displayed to the public.</Notes>
      </event>

问题是表单中有其他节点完全不同,有些节点几乎相同但位置不同。所以我想做一个if语句(我认为?),它检查整个文档是否与当前节点相同,然后将日期连接成一个节点,然后单独留下任何其他节点。这是我提出的代码

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

    <xsl:key name="title" match="event/*" use="concat(../@id, '-', localname())"/>  

    <xsl:template match="node()|@*">
            <xsl:copy>
                    <xsl:apply-templates select="node()|@*"/>
            </xsl:copy>
    </xsl:template>
        <xsl:for-each select="event/title">
            <xsl:when test = "(@title = preceding::*/@title)">
                This worked!
            </xsl:when>
        </xsl:for-each>
        <xsl:template match="event">
            <xsl:copy>
                    <xsl:apply-templates select="@*" />
                    <xsl:apply-templates select="title" />
                    <xsl:apply-templates select="RelatedLocations" />
                    <xsl:apply-templates select="Date" />
                    <xsl:apply-templates select="DateYear" />
                    <xsl:apply-templates select="DateMonth" />
                    <xsl:apply-templates select="DateDay" />
                    <xsl:apply-templates select="Body" />
                    <xsl:apply-templates select="AgeRanges" />
            </xsl:copy>
    </xsl:template>

这显然不起作用。所以请帮助并谢谢你。

0 个答案:

没有答案
相关问题