2015-12-31 2 views
3

Это должно быть довольно легко, но я новичок в XSLT, и мне сложно найти решение. Я получил следующий XML:Как добавить второй элемент с новым идентификатором?

<catalog> 
    <book id="1"> 
     <author>Mike</author> 
     <title>Tomas</title> 
    </book> 
</catalog> 

, и я пытаюсь добавить еще один book запись поверх него и изменить его id от 1 к 2. Я попробовал следующее, но не смог изменить значение атрибута.

<?xml version='1.0'?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > 

<xsl:template match="@id"> 
    <xsl:attribute name="id">2</xsl:attribute> 
    <xsl:apply-templates/> 
</xsl:template> 

<xsl:template match="book"> 
    <xsl:element name="book"> 
     <xsl:attribute name="id">1</xsl:attribute> 
     <xsl:element name="author">author1</xsl:element> 
     <xsl:element name="title">title1</xsl:element> 
    </xsl:element> 
    <xsl:copy-of select="."/> 
</xsl:template> 

</xsl:stylesheet> 

Любые предложения?

ответ

3

Использование apply-templates:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 

<xsl:template match="@id"> 
    <xsl:attribute name="id">2</xsl:attribute> 
</xsl:template> 

<xsl:template match="book"> 
    <book id="1"> 
     <author>author1</author> 
     <title>title1</title> 
    </book> 
    <xsl:copy> 
     <xsl:apply-templates select="@*"/> 
     <xsl:copy-of select="node()"/> 
    </xsl:copy> 
</xsl:template> 

</xsl:stylesheet> 

Вам нужно будет добавить

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

, чтобы убедиться, что каталог элемент или другие элементы и атрибуты копируются без изменений.

Таким образом, все предложения вместе привести в шаблонах

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

<xsl:template match="@id"> 
    <xsl:attribute name="id">2</xsl:attribute> 
</xsl:template> 

<xsl:template match="book"> 
    <book id="1"> 
     <author>author1</author> 
     <title>title1</title> 
    </book> 
    <xsl:copy> 
     <xsl:apply-templates select="@*"/> 
     <xsl:copy-of select="node()"/> 
    </xsl:copy> 
</xsl:template> 

, где мы могли бы укорачивать код для

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

<xsl:template match="@id"> 
    <xsl:attribute name="id">2</xsl:attribute> 
</xsl:template> 

<xsl:template match="book"> 
    <book id="1"> 
     <author>author1</author> 
     <title>title1</title> 
    </book> 
    <xsl:call-template name="identity"/> 
</xsl:template> 
+0

пытался это тоже. нет удачи:/ – Rakim

+0

http://xsltransform.net/3NJ38Zq есть мои предложения, результат выглядит хорошо для меня. –

+0

Извините, вы правы. Я поместил ваш код в неправильное место ... Спасибо! – Rakim

Смежные вопросы