Skaki
Skaki

Reputation: 33

Adding new element on top of XML data via XSLT

I am new to XML and XSLT so I need little bit of help. I have this kind of XML:

<Catalogue>
     <App id="1">
         <Car>BMW</Car>
         <BodyType>Sedan</BodyType>
         <PartType>Wiper</PartType>
         <PartNumber>1234</PartNumber>
     </App>
     <App id="2">
         <Car>Dodge</Car>
         <DriveType>FWD</DriveType>
         <PartType>Wiper</PartType>
         <PartNumber>5678</PartNumber>
     </App>
     <App id="3">
         <Car>Chevrolet</Car>
         <EngineVIN>G</EngineVIN>
         <PartType>Wiper</PartType>
         <PartNumber>9012</PartNumber>
     </App>
     <App id="4">
         <Car>VW</Car>
         <PartType>Wiper</PartType>
         <PartNumber>3456</PartNumber>
     </App>
</Catalogue>

I can't figure out how to write a XSLT to add top App with id=0 so it would look like this:

<Catalogue>
     <App id="0">
         <Car></Car>
         <BodyType></BodyType>
         <DriveType></DriveType>
         <EngineVIN></EngineVIN>
         <PartType></PartType>
         <PartNumber></PartNumber>
     </App>
     <App id="1">
         <Car>BMW</Car>
         <BodyType>Sedan</BodyType>
         <PartType>Wiper</PartType>
         <PartNumber>1234</PartNumber>
     </App>
     <App id="2">
         <Car>Dodge</Car>
         <DriveType>FWD</DriveType>
         <PartType>Wiper</PartType>
         <PartNumber>5678</PartNumber>
     </App>
     <App id="3">
         <Car>Chevrolet</Car>
         <EngineVIN>G</EngineVIN>
         <PartType>Wiper</PartType>
         <PartNumber>9012</PartNumber>
     </App>
     <App id="4">
         <Car>VW</Car>
         <PartType>Wiper</PartType>
         <PartNumber>3456</PartNumber>
     </App>
</Catalogue>

I am trying for couple of days now with no luck, so any help would be appreciated. I need this because when I want to import this XML into Access, for some reason if in first "App" all fields aren't defined (which occur in other "App"-s), they don't get imported.

Thank you!

Upvotes: 0

Views: 145

Answers (1)

Marcus Rickert
Marcus Rickert

Reputation: 4238

If you are satisfied with a fixed set of tags it can be done in XSLT 1.0 quite easily as follows:

<xsl:template match="/Catalogue">
  <Catalogue>

    <App id="0">
      <Car></Car>
      <BodyType></BodyType>
      <DriveType></DriveType>
      <EngineVIN></EngineVIN>
      <PartType></PartType>
      <PartNumber></PartNumber>
    </App>

    <xsl:copy-of select="App"/>

  </Catalogue>
</xsl:template>

Note that I added closing tags for <App>. These were missing in your XML file.

Upvotes: 1

Related Questions