2015-07-10 78 views
0

我有这样的结构副本父

<a href="xxx" class="box"> 
    <img src="1.jpg" alt="CBA" title="ABC" class="imgresp" height="204" width="307"> 
</a> 

我想要什么:
如果A-标签具有一流的“盒子”
然后从IMG公司,父标签复制标题属性

预期输出:

<a href="xxx" class="box" title="ABC"> 
    <img src="1.jpg" alt="CBA" title="ABC" class="imgresp" height="204" width="307"> 
</a> 
+0

你能编辑你的问题来显示你期望的输出吗?另外,如果您已经尝试了一些XSLT,那么即使它不起作用,您是否也可以证明这一点?谢谢! –

+0

用期望的输出更新 – user966660

回答

0

首先,XML需要很好地形成的,所以img标签需要关闭,否则将无法使用XSLT。

<a href="xxx" class="box"> 
    <img src="1.jpg" alt="CBA" title="ABC" class="imgresp" height="204" width="307" /> 
</a> 

假设真的是这样,你则需要在X SLT identity transform

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

它自己,它只是将所有节点读取,并从输入XML属性来输出XML按照你的情况,它为你带来99%的收益。

然后,您只需要一个模板来复制您需要的额外属性。在这种情况下,您需要一个与a标签匹配的模板,该模板将其复制,但也会添加额外的属性。

<xsl:template match="a[@class='box']"> 
    <xsl:copy> 
     <xsl:copy-of select="img/@title" /> 
     <xsl:apply-templates select="@*"/> 
     <xsl:apply-templates select="node()"/> 
    </xsl:copy> 
</xsl:template> 

或者,也许,这样,使用Attribute Value Templates创建属性

<xsl:template match="a[@class='box']"> 
    <a title="{img/@title}"> 
     <xsl:apply-templates select="@*|node()"/> 
    </a> 
</xsl:template> 

试试这个XSLT

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

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

    <xsl:template match="a[@class='box']"> 
     <a title="{img/@title}"> 
      <xsl:apply-templates select="@*|node()"/> 
     </a> 
    </xsl:template> 
</xsl:stylesheet> 
0

您可以创建相匹配的节点 'A' 和“模板img'及其属性。这个模板复制节点,做一个测试,如果有一个属性“类”以添加标题属性

<xsl:template match="a/@* |img/@* | a | img"> 
    <xsl:copy> 
     <xsl:if test="@class = 'box' "> 
      <xsl:attribute name="title" select="img/@title"/> 
     </xsl:if> 
     <xsl:apply-templates select="@* | node()"/> 
    </xsl:copy> 
    </xsl:template>