Suppose I have the following XML structure
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl"?>
<?xml-stylesheet type="text/xsl"?>
<WTT>
<Msg
UserText="Iswritable = true" >
</Msg>
<Test
BaseLvl="Msg" >
</Test>
<start
id = "1" >
</start>
<Msg
UserText="Iswritable = true" >
</Msg>
<Test
BaseLvl="Msg" >
</Test>
<Msg
UserText="WriteBuffers = 2">
</Msg>
<Test
BaseLvl="Txt" >
</Test>
<Msg
UserText="ReadBuffers = 1">
</Msg>
<end
id ="1" >
</end>
<start
id = "2" >
</start>
<Test
BaseLvl="sound" >
</Test>
<Test
BaseLvl="Msg" >
</Test>
<Msg
UserText="vertexbuffers = 1">
</Msg>
<end
id ="2" >
</end>
<Msg
UserText="vertexbuffers = 1">
</Msg>
</WTT>
Output :
<start
id = "1" >
</start>
<Msg
UserText="Iswritable = true" >
</Msg>
<Msg
UserText="ReadBuffers = 1">
</Msg>
<end
id ="1">
</end>
<start
id = "2" >
</start>
<Msg
UserText="vertexbuffers = 1">
</Msg>
<end
id ="2" >
</end>
The structure of the xml is not fixed and any tag can be put anywhere. Is there a way to do this? I tried using foreach and selecting only msg nodes but we cannot break the foreach in xslt. I just have to select all the <msg/>
tags between <start/>
and the <end/>
tags in separate groups.
The following stylesheet:
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:template match="/WTT">
<root>
<xsl:copy-of select="start | end | Msg[preceding-sibling::start[1]/@id = following-sibling::end[1]/@id]"/>
</root>
</xsl:template>
</xsl:stylesheet>
when applied to your XML input, will return:
<?xml version="1.0" encoding="UTF-8"?>
<root>
<start id="1"/>
<Msg UserText="Iswritable = true"/>
<Msg UserText="WriteBuffers = 2"/>
<Msg UserText="ReadBuffers = 1"/>
<end id="1"/>
<start id="2"/>
<Msg UserText="vertexbuffers = 1"/>
<end id="2"/>
</root>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.