Reading a list of Servers from XML using LINQ
Tuesday, July 22 2008 - sql-server, linq, xml
For one of the smaller projects I am working on I needed to get a list of database servers from a configuration file. To do this I have loaded up the servers and the database connection information into an XML File.
<DatabaseServers>
<Servers>
<Name>DatabaseServer1</Name>
<Server>DatabaseServer1</Server>
<Integrated>true</Integrated>
</Servers>
<Servers>
<Name>DatabaseServer2</Name>
<Server>DatabaseServer2\SQL2005</Server>
<Integrated>true</Integrated>
</Servers>
<Servers>
<Name>DatabaseServer3</Name>
<Server>DatabaseServer3\SQL2000</Server>
<Integrated>true</Integrated>
</Servers>
</DatabaseServers>
Next I decided to use linq to pull the information from the XML File, here is a simple Console Application that loads up the information from the file.
using System.Linq;
using System.Xml.Linq;
namespace ReadServersFromXML
{
class Program
{
static void Main(string[] args)
{
XDocument xml = XDocument.Load(@"DatabaseServerList.xml");
var query = from p in xml.Elements("DatabaseServers").Elements("Servers")
select p;
foreach (var record in query)
{
Console.WriteLine("Server: {0} {1}",
record.Element("Name").Value,
record.Element("Server").Value);
}
Console.ReadLine();
}
}
}
This is just a small sample of what did to complete the project. Moving forward I have configured a small SMO Application to connect to each Database server in the list and collect information on each of the servers to assist in documenting the systems.
