With that in mind, the first problem I encountered was the dissimilarities in formats between the appliactions. One striked my in particular, the application was driving it's data from and to a wrongly constructed XML file. It didn't had a single root, instead it had several different roots. Since I'm not trying to recreate the file but rather pull data from it, and XMLDocument doesn't allow multiple roots, I was in front of a dilema. To use a rather ugly and unperformant XMLReader to deal with the whole file and extract the information I wanted, or find my own method to convert it to an XMLDocument. Of course, I did the second.
That
This evolved into a single method that reads an pseudo-xml document from a text file, create a root (called "root" in this example) and add the elements of the file to it.
1 'Create our XMLDocument wich will hold our transformed file
2 Dim xr2 As New XmlDocument
3 'Loar a default root node
4 xr2.LoadXml("<root/>")
5
6 'Create a document fragment
7 Dim docFrag As XmlDocumentFragment = xr2.CreateDocumentFragment()
8
9 'Set the contents of the document fragment to our external file
10 docFrag.InnerXml = IO.File.ReadAllText("myfile.xml")
11
12 'Add the children of the document fragment to the original document
13 Dim currNode As XmlNode = docFrag.FirstChild
14 Dim nextNode As XmlNode = currNode.NextSibling
15
16 Do While nextNode IsNot Nothing
17
18 If nextNode.NodeType = XmlNodeType.Element Then
19 xr2.DocumentElement.AppendChild(nextNode)
20 nextNode = currNode.NextSibling
21
22 End If
23
24 nextNode = nextNode.NextSibling
25
26 Loop
27
28 '
29 Console.WriteLine("Display the modified XML...")
30 Console.WriteLine(xr2.InnerXml)
The code simply reads the file with IO.File.ReadAllText("myfile.xml"), and parse it to a XMLDocumentFragment.
The snippet may need some optimization, and may be hard to read, but it's working for my purpose.
In case you are wondering how to read it with an XMLReader, here is a possible way:
1 Public Sub GetXMLFragmentFromFile(ByVal filename As String)
2
3 'We need to tell XMLReader that we are expecting a fragment,
4 'that is a document with no root or multiple roots
5 Dim Xsettings As XmlReaderSettings = New XmlReaderSettings()
6 Xsettings.ConformanceLevel = ConformanceLevel.Fragment
7
8 'Let's read our file
9 Dim xr As XmlReader = XmlReader.Create("testfile.xml", Xsettings)
10
11 Do While xr.Read
12
13 If xr.NodeType = XmlNodeType.Element Then
14 'do something with the element found
15 End If
16
17 Loop
18
19 'Let's dispose our reader
20 xr.Close()
21
22 End Sub
Comments are welcome.