检索祖先属性
本文关键字:属性 祖先 检索 | 更新日期: 2023-09-27 18:01:33
我正在尝试为几个应用程序构建一个外部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,
我希望能够得到他们的值,从项目。祖先("服务器"),但我知道如何实现这一点。
你的意思是:
Server = project.Ancestors("Server").Single().Attribute("Name").Value;
Database = project.Ancestors("Database").Single().Attribute("Name").Value;
当然,这是假设对于给定的元素来说只有一个父元素