有选择地连接子节点的所有元素值

时间:2016-04-28 18:02:33

标签: xml xslt xslt-1.0

我有一个具有以下结构的XML

   <Group>
     <Note/>
     <Type>Anaerobic</Type>
   </Group>
   <Group>
     <Note>Note B</Note>
     <Type>Type B</Type>
   </Group>
   <Group>
     <Note>Note C</Note>
     <Type>Type C</Type>
   </Group>
   <Group>
     <Note>Note D</Note>
     <Type>Type D</Type>
   </Group>

我需要有选择地将节点的内容合并到一个元素中,如下所示。

<Group_Note> Note B Type B , Note c Type C , Note D Type D</Group_Note>

正如你所看到的那样,带有'Anaerobic'值的<Type>没有与其他人连接在一起。我可以使用以下代码将所有值转换为单个字符串。

<xsl:template name="Group">
      <xsl:for-each select="$thisNode//node()">
      <xsl:value-of select="name()"/>
      <xsl:if test="self::text()">
         <xsl:value-of select="."/>
      </xsl:if>
   </xsl:for-each>
</xsl:template> 

如何选择性地挑选和选择要连接的节点。非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

尝试这样的事情:

<xsl:template match="/*"> 
  <Group_Note>
    <xsl:apply-templates select="Group"/>
  </Group_Note>
</xsl:template> 

<xsl:template match="Group"/>

<xsl:template match="Group[Note != '' and Type != '']">
  <xsl:if test="preceding-sibling::Group[Note != '' 
                and Type != '']">,</xsl:if>
  <xsl:value-of select="concat(Note, ' ', Type)" />
</xsl:template>

答案 1 :(得分:0)

实现此目的的一种可能性是使用以下XSLT,它迭代非空Note元素并选择所有降序text()节点:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:template match="/root">    <!-- choose whatever root element you have -->
    <Group_Note>
      <xsl:for-each select="Group/*[../Note/text() != '']">
        <xsl:value-of select=".//text()"/>
        <xsl:if test="position()!=last()">  <!-- no space after last element -->
          <xsl:text> </xsl:text>
        </xsl:if>
      </xsl:for-each>
    </Group_Note>
  </xsl:template> 

</xsl:stylesheet>

输出结果为:

<?xml version="1.0"?>
<Group_Note>Note B Type B Note C Type C Note D Type D</Group_Note>

如果您插入

<xsl:value-of select="concat(Group[Note='']/Type,' ')" />

<xsl:for-each select="Group/*[../Note/text() != '']">之前,您将在开始时获得Anaerobic的{​​{1}}属性 - 然后累积其他Type个节点。

请注意,我通过检查空text()来区分Anaerobic节点与其他节点。如果您的要求不同,则必须调整谓词。

最终结果是:

<Note />
相关问题