1
<Menu>
  <Food>
    <Item>
      <Name>Waffles</Name>
      <Price>$9</Price>
      <Description>Try them with syrup *Additional Charge*</Description>
    </Item>
    <Item name="Pop-Tarts" price="$40" description="yummy"></Item>
  <Food>
<Menu>

I used the following XSLT to break up the second food item into three elements

<xsl:template match="/">
  <xsl:apply-templates select="Menu/Food" />
</xsl:template>

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

<xsl:template match="Item">
  <xsl:element name="{name()}">
    <!--This is what Im trying to fix-->
    <xsl:attribute name="id"></xsl:attribute>

    <xsl:for-each select="@*">
      <xsl:element name="{name()}">
        <xsl:value-of select="."/>
      </xsl:element>
    </xsl:for-each>
    <xsl:apply-templates select="* | text()"/>
  </xsl:element>
</xsl:template>

In the last template, how would I take the 'id' attribute for each 'Item' element and increment it for each new item?

This is what my current output looks like

<Food>
  <Item id="">
    <Name>Waffles</Name>
    <Price>$9</Price>
    <Description>Try them with syrup *Additional Charge*</Description>
  </Item>
  <Item id="">
    <name>Pop-Tarts</name>
    <price>$40</price>
    <description>yummy</description>
  </Item>
</Food>

2 Answers 2

2

How about:

XSLT 1.0

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

<xsl:template match="/Menu">
    <Food>
        <xsl:for-each select="Food/Item">
            <Item id="{position()}">
                <xsl:for-each select="@*">
                    <xsl:element name="{name()}">
                        <xsl:value-of select="."/>
                    </xsl:element>
                </xsl:for-each>
                <xsl:copy-of select="*"/>
            </Item>
        </xsl:for-each>
    </Food>
</xsl:template>

</xsl:stylesheet>

Note that XML is case-sensitive: Name is not the same as name.

Sign up to request clarification or add additional context in comments.

Comments

0

@michael.hor257k This code ends up not displaying anything in my output.

However using this part of your answer in my code got what I needed.

<xsl:template match="Food/Item">
  <Item id="{position()}">
    .....
  </Item>
</xsl:template>

1 Comment

You can see my answer working (with input corrected to be well-formed XML) here: xsltfiddle.liberty-development.net/jxDiMCh.

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.