0

xml 文件,如下所示

<Details>
<name>abc</name>
<profile>
<address>
<add1>ccc</add1>
<add2>bbb</add2>
<city>CA</city>
</address>
</profile>
</Details>

我想要如下输出: -

abc, ccc, CA, bbb

(我的意思是 city 将在 add2 之前出现,如果任何值为空白,那么它将相应地调整)

4

3 回答 3

1

如果要输出Details元素中的所有文本节点,只需使用xsl:for-each遍历它们,如果节点不是第一个节点,则使用position()函数输出逗号

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="xml" indent="yes"/>

   <xsl:template match="Details">
      <xsl:for-each select="//text()">
         <xsl:if test="position() > 1">
            <xsl:text>,</xsl:text>
         </xsl:if>
         <xsl:value-of select="." />
      </xsl:for-each>
   </xsl:template>
</xsl:stylesheet>

因此,如果您的某个元素中没有文本,它将不会得到输出或有额外的逗号。

于 2013-09-02T19:40:10.540 回答
0
<xsl:variable name="name"> 
     <xsl:value-of select="Details/name"/>
</xsl:variable>
<xsl:variable name="add1"> 
     <xsl:value-of select="Details/profile/address/add1"/>
</xsl:variable>
<xsl:variable name="add2"> 
     <xsl:value-of select="Details/profile/address/add2"/>
</xsl:variable>
<xsl:variable name="city"> 
     <xsl:value-of select="Details/profile/address/city"/>
</xsl:variable>
<xsl:value-of select="concat($name,',',$add1,',',$city,',',$add2)"/><br>

abc, ccc, CA, bbb如果 add1 返回,它将像这样显示 O/Pnull然后它将像这样显示abc, , CA, bbb

于 2013-09-02T11:06:02.320 回答
0

如果您使用的是 XSLT 2.0,您可以使用()运算符按您想要的顺序构造一个序列,然后使用separator属性 onxsl:value-of以逗号输出整个序列:

<xsl:template match="Details">
  <xsl:value-of select="(name, profile/address/add1, profile/address/city,
      profile/address/add2)" separator=", " />
</xsl:template>

如果您想过滤掉具有空值的元素(例如,如果文档包含<city/>),那么您可以使用 select 表达式上的谓词来做到这一点:

(name, profile/address/add1, profile/address/city,
      profile/address/add2)[normalize-space()]

谓词从序列中删除任何值为空或完全由空格组成的节点。

于 2013-09-02T21:47:20.677 回答