使用c#linq更改NHibernate配置文件

时间:2012-11-06 14:44:25

标签: c# .net xml linq nhibernate

让我们考虑以下web.config文件

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
  </configSections>
  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name='proxyfactory.factory_class'>NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle
      </property>
      <property name="connection.provider">
       NHibernate.Connection.DriverConnectionProvider
      </property>

     <property name="connection.connection_string">
         Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
      </property>
      <property name="dialect">
        NHibernate.Dialect.MySQLDialect
      </property>
      <property name="show_sql">
        false
      </property>
      <property name="hbm2ddl.keywords">none</property>
    </session-factory>
  </hibernate-configuration>
   <startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <qualifyAssembly partialName="MySql.Data" fullName="MySql.Data, Version=5.1.7.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
    </assemblyBinding>
  </runtime>

</configuration>

我的查询是更改 标记

中的值

旧值:

<property name="connection.provider">
       NHibernate.Connection.DriverConnectionProvider
      </property>

新值

<property name="connection.provider">
      Sample.DriverConnectionProvider
      </property>

为此我用过:

 XDocument doc = XDocument.Load("path to webconfig");

 var xElems = from x in doc.Descendants()
            where x.Name.LocalName == "property name=\"connection.provider\""
                  select x;

                foreach (var xElem in xElems)
                {
                    Console.WriteLine(xElem.Attribute("name"));
                }

但是当我查看文档时,我将xdoc中的视图视为:

//<property name="connection.provider" xmlns="urn:nhibernate-configuration-2.2">

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

XNamespace ns = "urn:nhibernate-configuration-2.2";
var xDoc = XDocument.Load(....);
var prop = xDoc.Descendants(ns+"property")
               .First(p=>p.Attribute("name").Value=="connection.provider");

prop.Value = "Sample.DriverConnectionProvider";