如何在xslt中的xml中存在任何属性时添加img标签?

时间:2017-01-27 10:01:36

标签: xml xslt xpath xslt-1.0

我想在img出现时添加data-type='image'代码。我们这样做是xslt吗?

这是我的代码(this comment):

<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
   <xsl:template match="/">
      <hmtl>
         <head>
            <title>New Version!</title>
         </head>
         <xsl:for-each select=".//a/cd">
            <li>
               <strong>
                  <xsl:value-of select="title" />
               </strong>
               <div>
                  <xsl:copy-of select="body/node()" />
               </div>
            </li>
         </xsl:for-each>
      </hmtl>
   </xsl:template>
   <xsl:template match="div[@data-type = 'image']">
      <img src="@src" />
   </xsl:template>
</xsl:transform>

输入

<a>
    <cd>
           <title>dddd</title>

        <body>
            <div col="1">d<p>ddd</p></div>
        </body>
    </cd>
     <cd>
       <title>ccc</title>
        <body>
            <div col="1">iii<p>ddd</p>

                <div data-type="image" src="abc.png" id='234'></div>
            </div>
        </body>
    </cd>
</a>

预期输出

<li><strong>dddd</strong><div>

    <div col="1">d
        <p>ddd</p>
    </div>

</div>
</li>
<li><strong>ccc</strong><div>

    <div col="1">iii
        <p>ddd</p>

         <div id="234">
        <img  src="abc.png"/>
         </div>

    </div>

</div>
</li>

1 个答案:

答案 0 :(得分:0)

您需要了解apply-templates和模板匹配,然后转换元素:

<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
   <xsl:output method="html" doctype-public="XSLT-compat" omit-xml-declaration="yes" encoding="UTF-8" indent="yes" />
   <xsl:template match="/">
      <hmtl>
         <head>
            <title>New Version!</title>
         </head>
         <xsl:for-each select=".//a/cd">
            <li>
               <strong>
                  <xsl:value-of select="title" />
               </strong>
               <div>
                  <xsl:apply-templates select="body/node()" />
               </div>
            </li>
         </xsl:for-each>
      </hmtl>
   </xsl:template>

   <xsl:template match="@* | node()">
       <xsl:copy>
           <xsl:apply-templates select="@* | node()"/>
       </xsl:copy>
   </xsl:template>

   <xsl:template match="div[@data-type = 'image']">
     <xsl:copy>
         <xsl:apply-templates select="@* except (@data-type, @src)"/>
         <img src="{@src}"/>
         <xsl:apply-templates/>
     </xsl:copy>
   </xsl:template>
</xsl:transform>