合并web.config和其他.config文件

时间:2013-07-18 15:21:35

标签: .net xml web-config

我动态地将对webservices的引用添加到项目中,我需要将它们的相关信息添加到web.config中。

svcutil优雅地添加包含“system.serviceModel”节点和子节点的配置文件。

我正在寻找的是如何将这些文件中的信息合并到现有的web.config中。我希望'configSource'属性可以提供帮助,但是,它不能用于“system.serviceModel”部分组,而只能用于它的内容。但是,与修改web.config本身相比,从所有配置中拆分“system.serviceModel”节点将需要相同甚至更多的解析。

我想知道,如果还有其他选项可以重用web.config中子配置文件中的数据?特别是,当涉及整个部门组?

1 个答案:

答案 0 :(得分:-1)

由于没有建议其他解决方案,我创建了一个手动修改web.config的函数,并从较小的配置中复制数据。

以防有人发现它有用或建议更好的方法:

# Changes web.config: adds into system.serviceModel group data for binding and for endpoint for the webservice
Function add-config-source
{
    Param($configFile)

        if(($configFile -eq "") -or ($configFile -eq $null))
        { $errors = $errors + " Error: path to webservice configuration file was not found. "; }

        # get data from the web service config file
        $webServiceConfigXml = [xml](get-content $configFile)
        # cloning elements that we need
        $bindingNodeClone = $webServiceConfigXml.SelectSingleNode("//binding").Clone();
        $endpointNodeClone = $webServiceConfigXml.SelectSingleNode("//endpoint").Clone();
        $serviceModelNodeClone = $webServiceConfigXml.SelectSingleNode("//system.serviceModel").Clone();

        # reading and modifying web.config
        $webConfigXml = New-Object xml
        # find the Web.config file
        $config = $project.ProjectItems | where {$_.Name -eq "Web.config"}
        # find its path on the file system
        $localPath = $config.Properties | where {$_.Name -eq "LocalPath"}
        # load Web.config as XML
        $webConfigXml.Load($localPath.Value)

        # select the node
        $configurationNode = $webConfigXml.SelectSingleNode("configuration")

        # check if 'system.serviceModel' node exists
        $serviceModelNode = $configurationNode.SelectSingleNode("system.serviceModel");

        if ($serviceModelNode -eq $null) 
        {
            $serviceModelNodeClone = $webConfigXml.ImportNode($serviceModelNodeClone, $true);
            $configurationNode.AppendChild($serviceModelNodeClone);
        }
        else
        {
            $existingBasicHttpBindingNode = $serviceModelNode.SelectSingleNode("//basicHttpBinding");
            $bindingNodeClone  = $webConfigXml.ImportNode($bindingNodeClone, $true);
            $existingBasicHttpBindingNode.AppendChild($bindingNodeClone);

            $existingClientNode = $serviceModelNode.SelectSingleNode("//client");
            $endpointNodeClone = $webConfigXml.ImportNode($endpointNodeClone, $true);
            $existingClientNode.AppendChild($endpointNodeClone);
            $configurationNode.AppendChild($serviceModelNode);
        }

        # save the Web.config file
        $webConfigXml.Save($localPath.Value)
}