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