0
在我的web应用程序中,我使用由xml文件(nhibernate.cfg.xml)配置的NHibernate。我需要从我的C#代码中的该文件读取连接字符串。我的代码正在工作,但我不喜欢它(特别是foreach!),我想直接查询xml文件。我试图用链接查询它,但我总是得到空节点。 这里是CFG文件:从C#读取NHibernate配置文件
<?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?
我试过这个,但root.Descendants(“属性”)给我“枚举没有结果”。 –
@DanieleArmanasco然后尝试XDocument.Load而不是 –
我试过XDocument,但得到了相同的结果... –