Using XMLTextReader to Read XML Data
The XMLTextReader can be much easier than the DOM or SAX to locate and filter data. It is ideal for large files since unlike the DOM it never loads an entire file in memory. Its design is so you can read through the file and when you notice items you want to grab you respond appropriately.
Here is code to read any XML File with an XMLTextReader object and see what types it emits. This toy program displays all the emitted types in a table for ANY XML FILE in this case the sample file @ http://www.learnasp.com/experiments/data/favebooks.xml, but you can easily run this on any XML file to know exactly what types an XMLTextReader will emit.
|
<%@trace="false" debug="true" %> <%@ Import Namespace="System.XML"%> <%@ Import Namespace="system.xml.xmlnodetype"%> <%@ Import Namespace="system.drawing"%> <script language="VB" runat="server"> Sub Page_Load(S As Object, E As EventArgs) trace.tracemode=TraceMode.SortByTime DIM Xmltr1 as XMLTextReader TRY Xmltr1=new XMLtextReader(server.mappath("/experiments/data/favebooks.xml")) DIM strTemp as string
DO WHILE Xmltr1.Read() trace.warn ("Value", Xmltr1.Value) 'trace.write ("Text", Xmltr1.Text) strTemp = "NodeType=" & Xmltr1.NodeType.ToString() IF Xmltr1.Name<>string.empty strTemp &= ";Name=" & Xmltr1.Name END IF IF Xmltr1.LocalName<>string.empty strTemp &= ";LocalName=" & Xmltr1.LocalName END IF IF Xmltr1.NamespaceURI<>string.empty strTemp &= ";NamespaceURI=" & Xmltr1.NamespaceURI END IF trace.write("",strTemp) TableCellsAdd(XMLtr1.Value,strTemp) IF Xmltr1.hasattributes trace.write ("attributecount", Xmltr1.attributecount) DO WHILE Xmltr1.MoveTonextAttribute() trace.write ("value;name",Xmltr1.name & ";" & Xmltr1.value) TableCellsAdd("attribute named <b>" & XMLtr1.Name & "</b>;value=<font color='red'>" & XMLtr1.Value & "</font>","") LOOP END IF LOOP CATCH ex1 as exception FINALLY Xmltr1.Close() END TRY End Sub
Sub TableCellsAdd(strParm1 as string,strParm2 as string) static intCellcounter as integer DIM cl1,cl2 as tablecell DIM rw1 as tablerow
cl1=new tablecell cl2=new tablecell cl1.controls.add(new literalcontrol(strParm1)) cl2.controls.add(new literalcontrol(strParm2)) rw1=new tablerow rw1.cells.add(cl1) rw1.cells.add(cl2) intCellCounter+=1 IF intCellCounter MOD 2 = 0 rw1.BackColor=Color.FromName("Silver") END IF tblXMLDetails.rows.add(rw1) End Sub
</script> <html><head> <title>XML Demo</title> </head> <body bgcolor="#FFFFFF"> <form runat="server"> <ASP:placeholder id="plcErr" runat="server" /> See The Trace For More Details <AsP:Table id="tblXMlDetails" runat="server" /> <ASP:placeholder id="plcEndofPage" runat="server" /> </form> </body></html> |
Visit http://www.learnasp.com for more Charles Carroll ASP related tutorials.