使用XSLT重命名XML元素和逗号分隔

时间:2017-02-04 03:16:07

标签: xml xslt xpath

我想要做的是将iavmNotice / title重命名为iavmNotice / iavmTitle:
这是我的XML:

<iavmNotice xmlns="http://stuff.com" noticeId="138643">
   <title>Cisco Vulnerability</title>
   <techOverview>
      <entry>
         <title>2012-2490</title>
         <description>Cisco ID 71.</description>
      </entry>
      <entry>
         <title>2012-2525</title>
         <description>Cisco ID 69.</description>
      </entry>
   </techOverview>
</iavmNotice>

这是我的尝试:

<xsl:template match="@* | node()">
  <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>
<xsl:template match="iavmNotice/title">
   <iavmTitle>
     <xsl:apply-templates select="@* | node()"/>
   </iavmTitle>
</xsl:template>
<xsl:template match="@iavmNotice/title">
  <xsl:attribute name="iavmTitle">
    <xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>

另外作为奖励有没有办法以逗号分隔导入techOverview / entry / title?将其导入2012-2490,2012-2525并删除说明。

1 个答案:

答案 0 :(得分:2)

XML文档的xmlns="http://stuff.com"根元素上的iavmNotice声明将整个文档放入http://stuff.com命名空间。

因此,您需要让您的样式表知道该命名空间,否则您的匹配项只需使用local-name()

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>
  <xsl:template match="*[local-name() = 'iavmNotice']/*[local-name() = 'title']">
     <iavmTitle>
       <xsl:apply-templates select="@* | node()"/>
     </iavmTitle>
  </xsl:template>
</xsl:stylesheet>