2

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!

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

In the template matching fruit you need to use <xsl:value-of select="@id"/> to select and output the value of the id attribute of the matched element.
@MartinHonnen Thanks, I hadn't spotted that mistake when I pasted it. I've fixed it now.
1

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.

2 Comments

does this mean you can't add a new attribute to a document element?
@Tcanarchy a document node is not an element. In the XPath data model the document node is a kind of virtual node that forms the root of the whole tree. The document node must have exactly one element child (the document element) but it can additionally have comments, processing instructions or whitespace-only text nodes before or after the single element (e.g. comments above the start tag of the document element). You can add attributes to the document element, but not to the root document node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.