To put it simply, I am having an issue when passing Stream objects to the XMLReader object's Create(Stream) function.
The following is a segment of code from the application I am creating to read encrypted and un-encrypted XML files stored locally.
Using fileStream As New FileStream(Filename, FileMode.Open, FileAccess.Read)
Dim reader As XmlReader = Nothing
Try
Dim encoder = GetEncoder()
Using cs As New CryptoStream(fileStream, encoder.CreateDecryptor(encoder.Key, encoder.IV), CryptoStreamMode.Read)
reader = XmlReader.Create(cs)
End Using
Catch ex As Exception
reader = XmlReader.Create(fileStream)
End Try
If reader IsNot Nothing Then
Try
Me.ReadXML(reader)
Finally
reader.Close()
reader = Nothing
End Try
End If
End Using
When using streams, I get the following exceptions on the first few iterations of the stream's read method inside the ReadXML function.
- System.Xml.XmlException: There are multiple root elements. Line 2, position 26. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String arg) at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read()
- System.Xml.XmlException: Data at the root level is invalid. Line 1, position 1. at System.Xml.XmlTextReaderImpl.Throw(Exception e) at System.Xml.XmlTextReaderImpl.Throw(String res, String arg) at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at System.Xml.XmlTextReaderImpl.ParseDocumentContent() at System.Xml.XmlTextReaderImpl.Read()
If I just decrypt the XML into plain-text and write it as file, I can use the XMLTextReader and pass the path of the decrypted file into the constructor to read the XML file just fine.
I know my XML file is formatted correctly as the XMLTextReader can parse through it with no issues when ONLY passing the file path. For reference, here is a snapshot of my XML file.
<?xml version="1.0"?>
<Books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="">
<Book name="Foo" author="Bar" />
<Book name="Bat" author="Widget" />
</Books>
I also know the ReadXML method works correctly for the same reason as above.
For reference my ReadXML method looks like this...
Sub ReadXML(reader As XmlReader)
Do While reader.Read()
Select Case reader.NodeType
Case XmlNodeType.Element
Select Case reader.Name.ToLower()
Case "x"
x=1
Case "y"
y=2
Case "z"
z=3
End Select
Case XmlNodeType.Text
x=a
y=b
z=c
Case XmlNodeType.EndElement
Select Case reader.Name.ToLower()
Case "a"
a=1
Case "b"
b=2
Case "c"
c=3
End Select
End Select
Loop
End Sub
Can anyone explain why creating an XMLReader with Stream objects would give me these exceptions? Does it have something to do with where the Stream starts reading?
Thanks in advance for your help!