我有兩種情況:
- 場景一:L節點有子節點SL
- 場景2:沒有子節點SL的L節點
<L Id="L1">如果在其他節點(如<SL id="L1S1">和)找到文本“L1”(),我需要形成多個 L 節點<pit ref="L1S1">。SL 節點(即<SL id="L1S1">)的 id 屬性是使用 中的“L1”形成的<L Id="L1">。另外,pit 節點的 ref 屬性(即<pit ref="L1S1">)是使用“L1” in 形成的<L Id="L1">,我需要檢查“L1”是否存在于 SL 的 id 屬性或pit 的 ref 屬性中,并形成所需的輸出。
輸入xml如下
<root>
<L Id="L1">
<test>ed</test>
<SL id="L1S1">
<check>
<AId>1</AId>
</check>
<MD>
<UnitNumber>1</UnitNumber>
</MD>
</SL>
<SL id="L1S2">
<check>
<AId>2</AId>
</check>
<MD>
<UnitNumber>2</UnitNumber>
</MD>
</SL>
</L>
<cp>
<current>
<Amt>20154.00</Amt>
</current>
<pi>
<pit ref="L1S1">
<value>123</value>
</pit>
<pit ref="L1S2">
<value>1232</value>
</pit>
</pi>
</cp>
</root>
預期輸出應該是:
<root>
<L Id="L1">
<SL id="L1S1">
<check>
<AId>1</AId>
</check>
<MD>
<UnitNumber>1</UnitNumber>
</MD>
</SL>
<pit ref="L1S1">
<value>123</value>
</pit>
</L>
<L Id="L1">
<SL id="L1S2">
<check>
<AId>2</AId>
</check>
<MD>
<UnitNumber>2</UnitNumber>
</MD>
</SL>
<pit ref="L1S2">
<value>1232</value>
</pit>
</L>
</root>
<root>
<L Id="L1">
<test>ed</test>
</L>
<cp>
<current>
<Amt>20154.00</Amt>
</current>
<pi>
<pit ref="L1S1">
<value>123</value>
</pit>
<pit ref="L1S2">
<value>1232</value>
</pit>
</pi>
</cp>
</root>
預期輸出應該是:
<root>
<L Id="L1">
<pit ref="L1S1">
<value>123</value>
</pit>
</L>
<L Id="L1">
<pit ref="L1S2">
<value>1232</value>
</pit>
</L>
</root>
任何人都可以幫助我提供適用于這兩種情況的解決方案嗎?
上面的 xslt 適用于第一個場景,但對于第二個輸入 xml 失敗,可能是我需要使用contains()或類似的東西,我不確定。
我正在使用 xslt1.0,并且在為第二種情況形成每個 L1 節點時遇到問題。
<xsl:key name="pit" match="pit" use="@ref" />
<xsl:copy>
<xsl:for-each select="L/SL">
<xsl:element name="{../@Id}">
<xsl:copy-of select="."/>
<xsl:copy-of select="key('pit', @Id)"/>
</xsl:element>
</xsl:for-each>
</xsl:copy>
uj5u.com熱心網友回復:
L/@Id我想在第二種情況下,和之間存在關系pit/@ref。現在我假設前兩個字符pit/@ref應該匹配L/@Id.
如果這是正確的,你可以嘗試這樣的事情:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
>
<xsl:output method="xml" indent="yes"/>
<xsl:key name="pit-SL" match="pit" use="@ref" />
<xsl:key name="pit-L" match="pit" use="substring(@ref,1,2)" />
<xsl:strip-space elements="*"/>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="L[SL]">
<xsl:apply-templates select="SL"/>
</xsl:template>
<xsl:template match="SL">
<L>
<xsl:copy-of select="parent::L/@Id"/>
<xsl:copy>
<xsl:copy-of select="@id"/>
<xsl:apply-templates select="node()"/>
<xsl:copy-of select="key('pit-SL',@id)"/>
</xsl:copy>
</L>
</xsl:template>
<xsl:template match="L[not(SL)]">
<xsl:apply-templates select="key('pit-L',@Id)">
<xsl:with-param name="L" select="."/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="pit">
<xsl:param name="L"/>
<L>
<xsl:copy-of select="$L/@Id"/>
<xsl:copy-of select="."/>
</L>
</xsl:template>
<xsl:template match="cp"/>
</xsl:stylesheet>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/454742.html
上一篇:XSD遵循一種或另一種元素格式
