基于值的XSLT分组实现技术求助(限定使用XSLT 1.0)
XSLT 1.0 Solution for Grouping & Dynamic Element Mapping
Hey there! I see you're working on an XSLT 1.0 transformation that requires grouping by the Id field, and you suspected Muenchian grouping was the way to go—you were absolutely right! The issue was likely in handling dynamic element generation and conditional field presence. Here's a solution that matches all your requirements:
XSLT Code
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns2="http://system.com/CustomUI" xmlns:ns3="http://www.system.com/xml/QE%20%%20%Points"> <xsl:output method="xml" indent="yes"/> <!-- Muenchian Grouping Key: Group assets by their Id value --> <xsl:key name="assetById" match="ns3:AssetMgmt-AssetXaQe" use="ns3:Id"/> <xsl:template match="/"> <Assets> <!-- Iterate over each unique Id group --> <xsl:for-each select="ns2:ListOfAssetMgmt-AssetXaQe/ns3:AssetMgmt-AssetXaQe[generate-id() = generate-id(key('assetById', ns3:Id)[1])]"> <QuotingEngineServicePointAssets> <!-- Output the MeterConfigurationId (mapped from Id) --> <MeterConfigurationId> <xsl:value-of select="ns3:Id"/> </MeterConfigurationId> <!-- Dynamically generate elements for each Name2/TextValue pair in the group --> <xsl:for-each select="key('assetById', ns3:Id)"> <xsl:element name="{ns3:Name2}"> <xsl:value-of select="ns3:TextValue"/> </xsl:element> </xsl:for-each> </QuotingEngineServicePointAssets> </xsl:for-each> </Assets> </xsl:template> </xsl:stylesheet>
Key Features Explained
Muenchian Grouping Done Right:
- The
<xsl:key>defines a grouping mechanism forns3:AssetMgmt-AssetXaQeelements using theirns3:Idvalue. - The condition
generate-id() = generate-id(key('assetById', ns3:Id)[1])selects only the first element of each unique Id group, ensuring we process each group exactly once.
- The
Dynamic Element Generation:
- Using
<xsl:element name="{ns3:Name2}">, we create output elements whose names directly match theName2values from the input (e.g.,Direction,MeterType), with content pulled fromTextValue.
- Using
Conditional Field Handling:
- This solution automatically ignores any fields (like
TimeOfUse,Segment) that aren't present in the input for a given Id group. No empty elements will be generated for missing fields, which aligns perfectly with your note.
- This solution automatically ignores any fields (like
Transformation Result
When applied to your input XML, this XSLT will produce the following output (with no empty elements for missing fields):
<Assets> <QuotingEngineServicePointAssets> <MeterConfigurationId>1</MeterConfigurationId> <Direction>Injection</Direction> <MeterType>YMR</MeterType> </QuotingEngineServicePointAssets> <QuotingEngineServicePointAssets> <MeterConfigurationId>2</MeterConfigurationId> <LoadProfile>Wind</LoadProfile> <Direction>Rotation</Direction> <MeterType>ZMR</MeterType> </QuotingEngineServicePointAssets> </Assets>
内容的提问来源于stack exchange,提问作者Admins
相关产品推荐
相关产品推荐

