繁体   English   中英

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

[英]how to add img tag when any attribute is present in xml in xslt?

我想在存在data-type='image'时添加img标签。我们能做xslt吗?

这是我的代码( http://xsltransform.net/pPJ8LVQ/3 ):

<?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>

您需要了解apply-templates和template匹配,然后才能转换元素:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM