Conditional replace in XML files

拜拜、爱过 提交于 2019-12-02 04:17:09
mklement0

Here's a quick fix, but note that a more robust solution would use PowerShell's XML parsing features: see Ansgar Wiecher's helpful answer:

Note:
- This answer assumes that the strings of interest do not conflict with syntactical elements of the XML document, such as element names and attribute names (which happens to work for the specific strings in question), which illustrates why using a real XML parser is the better choice.

$content = @'
<doc>
<title>web site</title>
<subtitle>web-site</subtitle>
<path>c:/web site/website.xml</path>
</doc>
'@

$modifiedContent = $content -replace '(^|[^/])web[ -]site([^/]|$)', '$1New Site$2'
# Replace 'web site' and 'web-site' if not preceded or followed by a '/'.
# Note: `web[ -]site` is the equivalent of `web site|web-site`

if ($modifiedContent -cne $content) { # If contents have changed, save.
  Out-File -InputObject $modifiedContent $file.FullName -Encoding utf8
}

It's usually far more efficient and far less error-prone to handle XML as XML. Select the nodes you want to update, then save the modified data back to a file.

$filename = 'C:\path\to\your.xml'

[xml]$xml = Get-Content $filename
$xml.SelectNodes('//*[self::title or self::subtitle]') |
    Where-Object { $_.'#text' -match 'web.site' } |
    ForEach-Object { $_.'#text' = 'New Site' }
$xml.Save($filename)

If you need to modify a substring of the node text you could do something like this:

$filename = 'C:\path\to\your.xml'

[xml]$xml = Get-Content $filename
$xml.SelectNodes('//*[self::title or self::subtitle]') |
    Where-Object { $_.'#text' -match 'web.site' } |
    ForEach-Object { $_.'#text' = $_.'#text' -replace 'web.site', 'New Site' }
$xml.Save($filename)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!