Splitting a large XML document using XmlTextReader in ASP.Net
I have done a project recently with a requirement to split a large XML document ( 2 MB file) and split it into small XML files. Obviously we can do this in different ways in ASP.net such as using a XSLT file to split the data or DOM object to separate the nodes.
After much experiment I found using XMLTextReader it is easy to split the large document. DOM approach which I tried was very slow. XMLTextReader wont load the large document to memory so it is faster than using XMLDOM to read the data.
Following is the example of how I tried XMLTextReader in ASP.net to split large XML document object in small pieces.
| Code: |
| Dim sXMLFile As String = "C:\PathTo\XMLFile.xml"
' XML Reader object Dim oXTR As New System.Xml.XmlTextReader(sXMLFile) Dim sName As String While oXTR.Read Select (oXTR.NodeType) Case System.Xml.XmlNodeType.Element If (oXTR.Name.Equals("student")) Then Dim doc As New System.Xml.XmlDocument() Dim node As XmlNode = doc.ReadNode(oXTR) Dim nodedata As XmlNode doc.AppendChild(node) doc.Save("C:\PathTo\resavingdata.xml") � you can pass unique name for file name here End If End Select ' break End While |
If you need to output the XML node as a string, you may try something like this:
| Code: |
| Dim sStringwriter As New System.IO.StringWriter
Dim doc As New System.Xml.XmlDocument() Dim node As XmlNode = doc.ReadNode(oXTR) Dim nodedata As XmlNode doc.AppendChild(node) doc.Save(sStringwriter) Response.write(sStringwriter.ToString) |
If you need to retrieve a child element from the node, you can try the following
| Code: |
| nodedata = doc.DocumentElement.SelectSingleNode("product/productid")
Response.Write(nodedata.Value & "<br />") |
Hope this example may help someone out there.
Commentaires
Enregistrer un commentaire