using System;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
public class XmlQueryExample {
public static void Main() {
using (SqlConnection con = new SqlConnection()) {
con.ConnectionString = "Data Source = localhost;" +
"Database = Northwind; Integrated Security=SSPI";
SqlCommand com = con.CreateCommand();
com.CommandType = CommandType.Text;
com.CommandText = "SELECT CustomerID, CompanyName" +
" FROM Customers FOR XML AUTO";
XmlReader reader = null;
try {
con.Open();
reader = com.ExecuteXmlReader();
while (reader.Read()) {
Console.Write(reader.Name);
if (reader.HasAttributes) {
for (int i = 0; i < reader.AttributeCount; i++) {
reader.MoveToAttribute(i);
Console.Write(" {0}: {1}",reader.Name, reader.Value);
}
reader.MoveToElement();
}
}
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
} finally {
if (reader != null) reader.Close();
}
}
}
}
|