假设我有以下XML结构
<?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>
输出:
<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>
xml的结构不固定,任何标签都可以放在任何地方。
有没有办法做到这一点?
我尝试使用foreach并仅选择msg节点但我们不能破坏xslt中的foreach。
我只需在不同的组中选择<msg/>
和<start/>
标记之间的所有<end/>
标记。
答案 0 :(得分:1)
以下样式表:
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>
应用于XML输入时,将返回:
<?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>