从C#读取NHibernate配置文件

时间:2014-01-27 18:09:05

标签: c# xml xml-parsing

在我的Web应用程序中,我使用的是由xml文件(nhibernate.cfg.xml)配置的NHibernate。我需要在C#代码中读取该文件中的连接字符串。我的代码正在运行,但我不喜欢它(特别是foreach!),我想以直接的方式查询xml文件。我试图用链接查询它,但我总是得到空节点。 这是cfg文件:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">
      NHibernate.Connection.DriverConnectionProvider
    </property>
    <property name="connection.driver_class">
      NHibernate.Driver.SqlClientDriver
    </property>
    <property name="connection.connection_string">
      Server=LEG\SQL12;initial catalog=DVR;user id=daniele;pwd=s;
    </property>
    <property name="dialect">
      NHibernate.Dialect.MsSql2008Dialect
    </property>
  </session-factory>
</hibernate-configuration>

这里是我的C#代码:

public static String GetConnectionString()
{
    if (String.IsNullOrEmpty(_connectionString))
    {
        XElement root = XElement.Load("hibernate.cfg.xml");
        var sessionFactoryNode = root.Elements().FirstOrDefault();  // session-factory
        if (sessionFactoryNode != null)
        {
            var properties = sessionFactoryNode.Elements();
            foreach (var property in properties)
            {
                if (property.Attribute("name").Value == "connection.connection_string")
                    _connectionString = property.Value.Trim();
            }
        }
    }
    return _connectionString;
}

如何获取查询xml的相同结果?

1 个答案:

答案 0 :(得分:0)

XElement root = XElement.Load("hibernate.cfg.xml");
var connString = root.Descendants("property")
             .Where(p => (string) p.Attribute("name") == "connection.connection_string")
             .Select(p => (string) p)
             .First();
相关问题