You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PowerShell更新XML节点属性值中的特定字符

PowerShell修改XML属性值的正确实现

原代码错误原因

  • -replace操作只会生成替换后的新字符串,你没有把这个新值赋值回节点的link属性,内存中的XML对象没有被修改,保存后的文件自然没有变化
  • XPath对节点名大小写敏感,原代码中路径写的system和实际XML里的<System>节点名不匹配,部分场景下会无法定位到目标节点
  • 使用SetAttribute时出现属性值全被替换为https,是因为你没有传入替换后的完整属性值,仅传入了https字符串

正确实现代码

$fileName = "C:\Project\XML-file\SampleXML.config"
# 读取XML时指定编码可避免中文乱码问题,可根据你的文件实际编码调整
$xmlContent = [xml](Get-Content -Path $fileName -Encoding UTF8)

# 修正XPath路径,将替换后的值赋值回节点属性
$xmlContent | Select-Xml -XPath 'Configuration/System/Address' | ForEach-Object {
    # 正则添加^标识仅替换开头的http,避免链接中间包含http时被误改
    $_.Node.link = $_.Node.link -replace '^http','https'
}

# 保存修改
$xmlContent.Save($fileName)

如果你偏好使用SetAttribute方法,正确写法如下

$xmlContent | Select-Xml -XPath 'Configuration/System/Address' | ForEach-Object {
    $originalLink = $_.Node.GetAttribute("link")
    $newLink = $originalLink -replace '^http','https'
    $_.Node.SetAttribute("link", $newLink)
}

内容的提问来源于stack exchange,提问作者Mari yah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:15:04