Add root element to repeated nodes in XML file using XSL

495 Views Asked by At

I have XML file has repeated nodes, But don't have root element as the following:

<my-element>AAA</my-element>
<my-element>BBB</my-element>
<my-element>CCC</my-element>

I wanna generate XML with root as the following:

<my-root>
    <my-element>AAA</my-element>
    <my-element>BBB</my-element>
    <my-element>CCC</my-element>
</my-root>

I typed the following code:

<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"/>
  <my-root>
        <xsl:for-each select="*">
            <xsl:copy-of select="."/>
        </xsl:for-each>
  </my-root>
</xsl:stylesheet>

But I received error because XML not formatted correctly:

The markup in the document following the root element must be well-formed.

I know the Input should have root element. But Is there way to set root element for repeated elements without root using XSL?

1

There are 1 best solutions below

0
Lucero On

Your input is not a well-formed XML document, which is why you get this error. However, it could be seen as a node-set.

Depending on the XSLT processor used you may therefore be able to somehow pass the node-set in as a parameter, but there is no "standard way" of doing that.

However, it's probably simpler to just wrap the input document into some element and process this afterwards, e.g. concat <root> + file-content + </root> into a temporary file and use that as input for the transformation.