There are several ways to "skin a cat" in .NET. XML Parsing is painful at best and sometimes the XML Document Object is the most painful. If you don't code to read and write XML every day, and I don't, then remembering all of the objects and their methods and things like XPath, etc, can be a real pain. ADO.NET gives you a simple way to parse XML, and DataSet ReadXML is easier than using the XML Document Object.
Let's say that in my application I have read an XML string from a database field and I need to parse it. The following code will allow me to access the fields from a DataRow by name and I can forget that it ever was in XML. Granted, the XML is very simple, but the object of the XML string is to show the use of ADO.NET to automatically parse your string.
In the following code, I am using an often overlooked .NET object, the StringReader. Also, althouth Intellisense on the ds.ReadXML does not show that StringReader is an overload parameter, it is. Since I already have a string of XML, the StringReader is the obvious way to create a Stream.
| string xml = "<file><field1>Field1 Data<field2>2"; StringReader sr = new StringReader(xml); DataSet ds = new DataSet(); ds.ReadXml(sr); DataRow dr = ds.Tables[0].Rows[0]; string s = string.Format("Field1: {0}", dr["field1"]); Console.WriteLine(s); s = string.Format("Field2: {0}", dr["field2"]); Console.WriteLine(s); |
| Field1: Field1 Data Field2: 2 |
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |