如何将VS2010 web.config转换应用于具有命名空间属性的元素?

gsc*_*ger 10 web-config transformation visual-studio-2010

我想使用新的VS2010 web.config转换功能来更改web.config文件中nhibernate配置中的连接字符串.相关的代码片段是这样的:

<?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="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="connection.driver_class">NHibernate.Driver.OracleDataClientDriver</property>
      <property name="connection.connection_string">(test connection string)</property>
      <property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
...
Run Code Online (Sandbox Code Playgroud)

我没有成功地尝试了以下转换:

<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    <hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
        <session-factory>
            <property name="connection.connection_string" xdt:Transform="Replace">(production connection string)</property>
        </session-factory>
    </hibernate-configuration>
</configuration>
Run Code Online (Sandbox Code Playgroud)

问题似乎是在nhibernate-configuration元素的xmlns属性中.

在部署期间,用(生产连接字符串)替换(测试连接字符串)的正确转换应该是什么?

And*_*son 15

我最近遇到了同样的问题 - 它是通过在转换文件中放置显式名称空间前缀来解决的

<configuration
               xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"
               xmlns:hib="urn:nhibernate-configuration-2.2"
              >
    <hib:hibernate-configuration>
        <hib:session-factory>
            <hib:property name="connection.connection_string" xdt:Transform="Replace">(production connection string)</hib:property>
        </hib:session-factory>
    </hib:hibernate-configuration>
</configuration>
Run Code Online (Sandbox Code Playgroud)

幸运的是,生成的转换后的web.config文件没有名称空间前缀(即它将nhibernate名称空间声明保留在与原始web.config文件相同的位置并正确命名所有节点)


小智 7

答案可能有点晚了,但既然我也需要这个,我想我会发布一个对我有用的答案,如果其他人偶然发现这个问题.

您需要将xdt:Locator与xpath表达式结合使用才能获得正确的节点.所以这样的事情应该有效.

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
   <session-factory>
      <property name="connection.connection_string" xdt:Locator="XPath(//*[local-name()='hibernate-configuration']//*[local-name()='property'][@name='connection.connection_string'])" xdt:Transform="Replace">(production connection string)</property>
   </session-factory>
</hibernate-configuration>
Run Code Online (Sandbox Code Playgroud)

可能有更好的xpath表达式,但这对我有用.

唯一的问题,不是那么重要,被替换的节点将在节点上重新声明一个命名空间.因此,替换的节点实际上在最终输出中看起来像这样.

<property name="connection.connection_string" xmlns="urn:nhibernate-configuration-2.2">(production connection string)</property>
Run Code Online (Sandbox Code Playgroud)