3
我正在尝试为几个应用程序构建一个外部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(“服务器”),但我不知道如何来实现这一目标。
理解大部分LINQ to XML在具有祖先轴的XPath上构建也可能有帮助。 – GalacticCowboy 2013-02-28 19:38:31
我也假设。而这正是需要的。 – EZE 2013-02-28 19:39:41