我需要转换一个XML,其中转换规则应仅适用于某些元素,而rest应该按原样复制。 下面是源和预期的xml块。
<Object class="Item" version="1.0" distName="A-1/B-1/Item-0">
<p name="sDate">2013-02-11T00:00:00+02:00:00</p>
<p name="present">1</p>
<p name="stopD">2013-02-21T00:00:00+02:00:00</p>
<p name="id">CPU</p>
</Object>
<Object class="Period" version="1.0" distName="A-1/B-1/Item-0/Period-0">
<p name="sHour">0</p>
<p name="sMinute">0</p>
<p name="interval">1</p>
<p name="day">0</p>
</Object>
到
<Object class="Items" distName="A-1/B-1/Items-0">
<p name="IsPresent">1</p>
<p name="StartDate">08-11-2012</p>
<p name="StopDate">29-11-2012</p>
<list name="TimePeriod">
<item>
<p name="id">1</p>
<p name="StartTime">00:00</p>
<p name="day">0</p>
<p name="interval">15</p>
</item>
</list>
<list name="TypeRef">
<p>Diameter</p>
</list>
1.在Object元素上方应该与基于具有父子层次结构的distName的另一个Object元素组合。例如: A-1 / B-1 / Item-0 , A-1 / B-1 / Item-0 / Period-0
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:1)
您的预期结果中的某些项目似乎与输入不匹配,但这可能会帮助您从A点到达B点。我还没有在这里进行日期转换,我不知道TypeRef是什么你的来源。
<xsl:template match="Object[@class='Item']">
<xsl:variable name="mainobj" select="."/>
<xsl:variable name="distName" select="@distName"/>
<Object class="Items" distName="{$distName}">
<p name="IsPresent">
<xsl:value-of select="p[@name='present']"/>
</p>
<p name="StartDate">
<xsl:value-of select="p[@name='sDate']"/>
</p>
<p name="StopDate">
<xsl:value-of select="p[@name='stopD']"/>
</p>
<xsl:variable name="objperiod" select="//Object[starts-with(@distName,$distName)][not(.=$mainobj)]"/>
<xsl:for-each select="$objperiod">
<list name="TimePeriod">
<item>
<p name="id">
<xsl:value-of select="p[@name='id']"/>
</p>
<p name="StartTime">
<xsl:value-of select="concat(format-number($objperiod/p[@name='sHour'],'00'),':',format-number($objperiod/p[@name='sMinute'],'00'))"/>
</p>
<p name="day">
<xsl:value-of select="$objperiod/p[@name='day']"/>
</p>
<p name="interval">
<xsl:value-of select="$objperiod/p[@name='interval']"/>
</p>
</item>
</list>
</xsl:for-each>
</Object>
</xsl:template>
这产生以下结果:
<Object class="Items" distName="A-1/B-1/Item-0">
<p name="IsPresent">1</p>
<p name="StartDate">2013-02-11T00:00:00+02:00:00</p>
<p name="StopDate">2013-02-21T00:00:00+02:00:00</p>
<list name="TimePeriod">
<item>
<p name="id">CPU</p>
<p name="StartTime">00:00</p>
<p name="day">0</p>
<p name="interval">1</p>
</item>
</list>
<list name="TimePeriod">
<item>
<p name="id"/>
<p name="StartTime">00:00</p>
<p name="day">0</p>
<p name="interval">1</p>
</item>
</list>
<list name="TimePeriod">
<item>
<p name="id"/>
<p name="StartTime">00:00</p>
<p name="day">0</p>
<p name="interval">1</p>
</item>
</list>
</Object>