2012-06-06 30 views
0

鉴于XML如新节点添加到盛大父节点:XSL在XML

<a> 
    <b> 
    <c>some keyword</c> 
    </b> 
</a> 

我需要新节点的情况下,增加的父节点,如果节点C包含文本“关键字”所以它看起来像

<a> 
    <b> 
    <c>some keyword</c> 
    </b> 
</a> 
<x> new node X </x> 

我可以配合表情文字:

<xsl:template match="//a/b/c[matches(text(),'\.*keyword\.*')]"> 
    <xsl:copy-of select="."/> 
    <xsl:element name="x"> 
    <xsl:text> new node </xsl:text> 
    </xsl:element> 
</xsl:template> 

,这导致

<a> 
    <b> 
    <c>some keyword</c> 
    <x> new node X </x> 
    </b> 
</a> 

我该如何解决呢?

+0

你的意思是你想的“X”节点添加到“一”家长,不要节点“a”,对不对? – toniedzwiedz

+0

是,将纠正后 – jdevelop

回答

1

您必须添加x元素同时匹配a的母公司。您可以引用谓词中的任何子元素或属性。我的意思是你必须在复制它的时候先看看父母的内容。在复制a,b或c元素时执行此操作太迟了。

下面的样式表应该做的伎俩。我没有对我的任何XSLT2.0功能的处理器,现在,所以我不能检查,但你应该能够看到它的逻辑。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet version="2.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:template match="*"> 
    <xsl:element name="{name()}"> 
     <xsl:apply-templates ></xsl:apply-templates> 
    </xsl:element> 
</xsl:template> 
<xsl:template match="//*[matches(a/b/c/text() , 'keyword')]"> 
    <xsl:element name="{name()}"> 
     <xsl:apply-templates ></xsl:apply-templates> 
     <xsl:element name="x"> 
      <xsl:text> new node </xsl:text> 
     </xsl:element> 
    </xsl:element> 
</xsl:template> 

+0

我也略有不同,但发电机密封想法是清楚的。 http://stackoverflow.com/questions/3672992/how-to-select-the-grandparent-of-a-node-using-xslt这是有用的。 – jdevelop