xml - Powershell使用-replace编辑节点中的部分文本?
问题描述
我正在尝试使用 -replace 或等效于根据条件搜索指定节点的东西来编写 powershell 脚本,并仅将部分文本替换为其他文本。这甚至可能吗?
这是我尝试根据“路径”的值编辑的一些示例节点:
<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>
下面是我当前的代码设置,用于替换整个字符串,但 id 更喜欢用“content”替换“text”,因此节点现在会说“Some Content Here”。我尝试使用 -replace 但我无法让它正常工作。
#defaults
$xml = [xml](Get-Content $file.FullName)
$node = $xml.DTSConfiguration.Configuration
#updating individual attributes
$pathVar = "var1"
$confVal = ""
($xml.DTSConfiguration.Configuration | Where-Object {$_.Path -like ("*{0}*" -f $pathVar)}).ConfiguredValue = ("{0}" -f $confVal)
$xml.Save($file.FullName)
解决方案
处理 XML 数据时,XPath通常是访问节点及其属性的最通用方式。在您的情况下,您希望选择其属性包含变量中定义的子字符串<ConfiguredValue>
的节点的子节点。<Configuration>
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
运算符执行正则表达式替换。
推荐阅读
- sql - 如何确定现有访问关系的 ON UPDATE/DELETE 操作?
- python - BeautifulSoup 返回 noneType
- php - 重置 URL 查询参数的表单帖子的逻辑?
- javascript - 您如何使用“onClick”显示总计?
- javascript - Javascript Google Signin 未捕获异常 [object Object]
- python - matplotlib yaxis 乱序
- java - onResume 重新开始播放背景音乐不起作用
- c# - 仅在 EF Core 中为“true”创建唯一约束
- python - 如何为 python 脚本测试系统(使用 stdio)实现服务器?
- python - 如何过滤 JSON 数据?