Xml Powershell是否使用-replace编辑节点中的部分文本?

Xml Powershell是否使用-replace编辑节点中的部分文本?,xml,powershell,Xml,Powershell,我正在尝试使用-replace或其他等效工具编写powershell脚本,以根据条件搜索指定节点,并仅将部分文本替换为其他文本。这可能吗 下面是我试图根据“Path”的值编辑的一些示例节点: <Configuration ConfiguredType="Property" Path="\Package.Variables[User::var1].Properties[Value]" ValueType="String"> <ConfiguredValu

我正在尝试使用-replace或其他等效工具编写powershell脚本,以根据条件搜索指定节点,并仅将部分文本替换为其他文本。这可能吗

下面是我试图根据“Path”的值编辑的一些示例节点:

<Configuration ConfiguredType="Property" Path="\Package.Variables[User::var1].Properties[Value]" 
    ValueType="String">
        <ConfiguredValue>Some Text Here</ConfiguredValue>
</Configuration>

<Configuration ConfiguredType="Property" Path="\Package.Variables[User::var2].Properties[Value]" 
    ValueType="String">
        <ConfiguredValue>More Text Here</ConfiguredValue>
</Configuration>

如果我理解您的问题,您将用字符串值替换字符串标记

如果这是真的,您可以将xml视为字符串并执行如下替换:

$token = 'text'
$value = 'content'
$content = Get-Content $file.FullName
$content = $content.Replace($token, $value)
$content | Out-File $file.FullName
请记住,您的令牌应该是唯一的,因为它将替换令牌的所有实例

如果无法识别唯一标记,则可以在从xml路径中选择值后对字符串进行替换

(($xml.DTSConfiguration.Configuration | Where-Object {$_.Path -like ("*{0}*" -f $pathVar)}).ConfiguredValue = ("{0}" -f $confVal)).Replace('text','content')

如果我理解您的问题,您将用字符串值替换字符串标记

如果这是真的,您可以将xml视为字符串并执行如下替换:

$token = 'text'
$value = 'content'
$content = Get-Content $file.FullName
$content = $content.Replace($token, $value)
$content | Out-File $file.FullName
请记住,您的令牌应该是唯一的,因为它将替换令牌的所有实例

如果无法识别唯一标记,则可以在从xml路径中选择值后对字符串进行替换

(($xml.DTSConfiguration.Configuration | Where-Object {$_.Path -like ("*{0}*" -f $pathVar)}).ConfiguredValue = ("{0}" -f $confVal)).Replace('text','content')

使用XML数据时,通常是访问节点及其属性的最通用的方法。在本例中,您希望选择
节点的
子节点,该节点的
Path
属性包含变量
$pathVar
中定义的子字符串

$xpath = "//Configuration[contains(@Path, '$pathVar')]/ConfiguredValue"
$node  = $xml.SelectSingleNode($xpath)
$node.'#text' = $node.'#text'.Replace('Text', 'Content')
请注意XPath表达式和
Replace()
方法都区分大小写

也可以使用
-replace
运算符(默认情况下不区分大小写):

$node.'#text' = $node.'#text' -replace 'Text', 'Content'

但是,
Replace()
方法提供了更好的性能,因为它执行简单的字符串替换,而
-Replace
操作符执行正则表达式替换。

处理XML数据时,通常是访问节点及其属性的最通用方法。在本例中,您希望选择
节点的
子节点,该节点的
Path
属性包含变量
$pathVar
中定义的子字符串

$xpath = "//Configuration[contains(@Path, '$pathVar')]/ConfiguredValue"
$node  = $xml.SelectSingleNode($xpath)
$node.'#text' = $node.'#text'.Replace('Text', 'Content')
请注意XPath表达式和
Replace()
方法都区分大小写

也可以使用
-replace
运算符(默认情况下不区分大小写):

$node.'#text' = $node.'#text' -replace 'Text', 'Content'
但是,
Replace()
方法提供了更好的性能,因为它执行简单的字符串替换,而
-Replace
操作符执行正则表达式替换