gpt4 book ai didi

c# - 检索祖先属性

转载 作者:数据小太阳 更新时间:2023-10-29 02:31:05 24 4
gpt4 key购买 nike

我正在尝试为多个应用程序构建一个外部 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>

将有一个辅助连接,以防主连接出现故障。我想要做的是搜索 Project: Food 获取其登录信息、数据库和服务器。我可以用这段代码来做:

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") 中获取它们的值,但我知道如何实现这一点。

最佳答案

你的意思是:

Server = project.Ancestors("Server").Single().Attribute("Name").Value;
Database = project.Ancestors("Database").Single().Attribute("Name").Value;

当然,这是假设给定元素永远只有一个祖先。

关于c# - 检索祖先属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com