Conditional replace in XML files

青春壹個敷衍的年華 提交于 2019-12-02 12:00:14

问题


I'm replacing a text in XML files recursively using PowerShell. The script is working fine in replacing. However the XML files also have file paths which should not be replaced. This is the script currently being used

if ( $content -match ' web site | web-site ' ) {
    $content -replace ' web site ',' New Site ' -replace ' web-site ',' New Site ' |
        Out-File $file.FullName -Encoding utf8

For example if the XML file has

<title>web site</title>
<subtitle>web-site</subtitle>
<path>c:/web site/website.xml</path>

the expected output is should look like below. The matching text in file paths should be ignored. How can I add a condition to ignore the string if its between /web site/ or /web-site.xml?

<title>New Site</title>
<subtitle>New Site</subtitle>
<path>c:/web site/website.xml</path>

回答1:


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
}



回答2:


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)


来源:https://stackoverflow.com/questions/38534986/conditional-replace-in-xml-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!