2017-05-25 112 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请查看添加的说明。 –