我正在尝试为多个应用程序构建一个外部 XML 配置文件,以容纳它们的连接字符串。该文件看起来像这样:
<?xml version="1.0" encoding="ISO-8859-1"?>
<configuration>
<Connection Name = "Primary">
<Server Name = "DisneyWorld">
<Database Name ="MagicKingdom">
<Project Name ="Rides">
<Login Username="Mickey" Password="Mouse" Encrypted="False"/>
</Project>
<Project Name = "Food">
<Login Username="Goofy" Password="123456" Encrypted="True"/>
</Project>
<Project Name ="Shows">
<Login Username ="Minnie" Password="Mouse" Encrypted="False"/>
</Project>
</Database>
</Server>
<Server Name = "Epcot">
<Database Name ="LandOfTomorrow">
<Project Name = "Innovation">
<Login Username="Daffy" Password="Duck" Encrypted="False"/>
</Project>
</Database>
</Server>
</Connection>
</configuration>
将有一个辅助连接,以防主要连接断开。我想要做的是搜索项目:食物获取其登录信息、数据库和服务器。我可以用这段代码来做:
XDocument doc = XDocument.Load(path);
var query = from connection in doc.Descendants("Connection")
where connection.Attribute("Name").Value == "Primary"
from project in connection.Descendants("Project")
where project.Attribute("Name").Value == targetProject
select new
{
Server = connection.Element("Server").Attribute("Name").Value,
Database = project.Parent.Attribute("Name").Value,
UserName = project.Element("Login").Attribute("Username").Value,
Password = project.Element("Login").Attribute("Password").Value,
Encrypted = project.Element("Login").Attribute("Password").Value
};
该代码运行良好,但它被硬编码为当前结构。上线
Server = connection.Element("Server").Attribute("Name").Value,
和
Database = project.Parent.Attribute("Name").Value,
我希望能够从 project.Ancestors("Server") 中获取它们的值,但我确实了解如何实现这一点。