通过从属性文件中读取来更新 xml 文件中的属性值 [英] update property value in xml file by reading it from properties file
问题描述
我有一个包含以下条目的属性文件:-
I have a properties files with below entries:-
DBconn=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;
WebErrString=off
XLVXProvidername=Client.Data.OraclieClient
我有另一个 xml 文件,如下所示,@@@@ 之间有上述属性名称.
I have another xml file as below with above properties name between @@ @@.
<?xml version="1.0"?>
<ConfigValues>
<Connstring>
add name="connXLVX" connectionString="Data Source=@@DBconn@@" providerName="@@XLVXProvidername@@"/>
</Connstring>
<WebErrormode="@@WebErrString@@" />
</ConfigValues>
我可以从配置文件中更新给定的属性,如下所示,但无法遍历@@@@ 之间的所有属性并更新它们.
I am able to update given property from the config file as below but unable to loop through all the properties between @@ @@ and update them.
$proppath='C:\Desktop\dev.properties'
$webconfigpath= 'C:\Desktop\xml.config'
$AppProps = @{}
$AppProps = convertfrom-stringdata (get-content $proppath -raw)
(Get-Content $webconfigpath) -replace "@@DBconn@@", $AppProps["DBconn"] | Set-Content $webconfigpath
推荐答案
您需要的是能够根据给定匹配项的特定文本动态确定每个替换字符串:
What you need is the ability to dynamically determine each substitution string, based on the specific text of a given match:
在 PowerShell (Core) 6.1+ 中,您可以使用以下方法:
In PowerShell (Core) 6.1+, you can use the following approach:
(Get-Content -Raw $webconfigpath) -replace '@@(\w+)@@', {
$AppProps[$_.Groups[1].Value]
} | Set-Content $webconfigpath
每个匹配项都作为 传递System.Text.RegularExpressions.Match
实例到脚本块 ({ ... }
),可以通过 自动$_
变量.
Each match is passed as a System.Text.RegularExpressions.Match
instance to the script block ({ ... }
), where it can be accessed via the automatic $_
variable.
在早期版本中,包括在 Windows PowerShell 中,-replace
运算符尚不支持基于脚本块的替换,直接使用底层 .NET API 是必需的:
In earlier versions, including in Windows PowerShell, where script-block-based substitutions aren't yet supported with the -replace
operator, direct use of the underlying .NET APIs is required:
[regex]::Replace((Get-Content -Raw $webconfigpath), '@@(\w+)@@', {
param($m)
$AppProps[$m.Groups[1].Value]
}) | Set-Content $webconfigpath
这篇关于通过从属性文件中读取来更新 xml 文件中的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!