2017-05-25 113 views
0

上層標籤檢查情況我有這樣的要求,我只需要填入下<Section><Group>標籤,如果下<Data><Group>標籤不存在。我無法獲得我想要的正確輸出。例如:在XSLT 2.0

INPUT

<Record> 
<Data> 
    <ID>1234DFD57</ID> 
    <Group> 
     <abc-KD>243fds</abc-KD> 
    </Group> 
    <Section> 
     <ID>33-2311</ID> 
     <Group> 
      <abc-KD>NORM</abc-KD> 
     </Group> 
     <Date>2017-03-25</Date> 
    </Section> 
    <Date>2017-03-25</Date> 
</Data> 
</Record> 

預期輸出

<Record> 
<Data> 
    <ID>1234DFD57</ID> 
    <Group> 
     <abc-KD>243fds</abc-KD> 
    </Group> 
    <Section> 
     <ID>33-2311</ID> 
     <Date>2017-03-25</Date> 
    </Section> 
    <Date>2017-03-25</Date> 
</Data> 
</Record> 

XSLT:

<xsl:stylesheet version="2.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="@*|node()"> 
    <xsl:copy> 
     <xsl:apply-templates select="@*|node()"/> 
    </xsl:copy> 
</xsl:template> 
<xsl:template match="Section"> 
    <xsl:copy> 
     <xsl:copy-of select="ID"/> 
     <xsl:if test="normalize-space(string(../Group)) = ''"> 
      <xsl:copy-of select="Group"/> 
     </xsl:if> 
     <xsl:copy-of select="Date"/> 
    </xsl:copy> 
</xsl:template> 
</xsl:stylesheet> 

您的意見非常感謝。

Regards,

回答

0

您當前的樣式表完成這項工作。更有效的方法是:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> 
    <!-- identity transform template --> 
    <xsl:template match="@*|node()"> 
     <xsl:copy> 
      <xsl:apply-templates select="@*|node()"/> 
     </xsl:copy> 
    </xsl:template> 
    <!-- do nothing for the Group --> 
    <xsl:template match="Section[normalize-space(parent::Data/Group) != '']/Group"/> 
</xsl:stylesheet> 

身份轉換模板是一個副本中的XML的每個節點,而在文檔順序遞歸地處理它們,因爲它是。 第二個模板與Group元素匹配所需的條件,並對它做任何事情,因此在輸出中省略它們。

x路在@match是卓有成效:
Section[normalize-space(parent::Data/Group) != '']/Group

Data下那些Section/Group元件,其Group不存在或具有空值(不包括空格字符)相匹配。

+0

謝謝!有效。你能解釋一下如何使用模板嗎?對不起,我仍然在學習基本部分,我無法理解你所做的解決方案。謝謝。 –

+0

@AltheaVeronica請查看添加的說明。 –