检索祖先属性

时间:2013-02-28 19:25:17

标签: c# xml configuration-files

我正在尝试为多个应用程序构建外部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”)中获取他们的值,但我确实知道如何实现这一点。

1 个答案:

答案 0 :(得分:3)

你的意思是:

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

当然,假设 只是一个给定元素的单个祖先。