简体   繁体   中英

XSLT: Creating new attribute with value of another attribute

I am transforming one XML into another. Let's say the XML we start from looks like this

<fruit id="123">
  <apple></apple>
  <banana></banana>
  <lemon></lemon>
</fruit>

Now in my transformed XML I want to create a new attribute with the value of the id attribute from my old XML.

I tried to do this like this:

 <xsl:template match="fruit">
    <xsl:attribute name="reference">
         <xsl:value-of select="fruit/@id"/>   
    </xsl:attribute>
 </xsl:template>

I get this error:

cannot create an attribute node whose parent is a document node

Can somebody explain to me what I'm doing wrong, since I don't understand the error. A solution would be nice.

Thank you!

The problem is that Document Nodes cannot have attributes, and you are not creating an element in the output tree for the attribute to be applied to. A Document Node must also have a single Element child.

Something like the following should work.

<xsl:template match="fruit">
    <fruit>
        <xsl:attribute name="reference">
             <xsl:value-of select="@id"/>   
        </xsl:attribute>
    </fruit>
 </xsl:template>

The error message is telling you that you can't create an attribute node here, because there's no element for it to belong to. Attribute nodes can only be created when you're inside an element (in the output sense) and you haven't yet created any child nodes (elements, text nodes, comments or processing instructions) under that element.

Aside from this, your XPath is wrong - you're inside a template matching the fruit element, so the path to the id attribute is just @id , not fruit/@id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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