Search code examples
vb.netxsltxmldocument

Error "Data at the root level is invalid" after transformation, while doing a LoadXML


I am trying to do some XSLT transformation, to convert an XML to XML, using the following lines of code. When i try to create an XMLDocument object from the transformed XML i am getting an error

Data at the root level is invalid. Line 1, position 1.

 Dim outputXML As New XmlDocument

        Dim stream As New MemoryStream
        Dim writer As XmlTextWriter = New XmlTextWriter(stream, System.Text.UnicodeEncoding.UTF8)

        Dim navigator As XPathNavigator = illustratePlusXML.CreateNavigator()
        Dim transormer As XslCompiledTransform = New XslCompiledTransform()
        transormer.Load(ConfigurationManager.AppSettings("XSLT_File_Path"))
        transormer.Transform(navigator, Nothing, writer)

        Dim output As String = System.Text.UnicodeEncoding.UTF8.GetString(stream.ToArray())
        outputXML.LoadXml(output)

        Return outputXML

I could find a special character(square box), i persume this is causing the error. attached snapshot of the output xml. Can somebody please suggest ?

output xml with special character


Solution

  • If you want to populate an XmlDocument as the result of an XSLT transformation then simply do

    Dim resultDoc As New XmlDocument()
    Using xw As XmlWriter = resultDoc.CreateNavigator().AppendChild()
            Dim navigator As XPathNavigator = illustratePlusXML.CreateNavigator()
            Dim transormer As XslCompiledTransform = New XslCompiledTransform()
            transormer.Load(ConfigurationManager.AppSettings("XSLT_File_Path"))
            transormer.Transform(navigator, Nothing, xw)  
            xw.Close()
    End Using
    

    There is no need to use a MemoryStream. If you really think you need to use a MemoryStream then make sure you reset its Position to 0 before calling the Load method.