Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've parsed the XML file and I have these strings. So, I need to replace the GUID "{87440A4C-1FE4-412E-80C3-74E4F97A31B4}" with a new GUID "{BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}". How can I save XML after these changes?

Strings which I parsed:

C:ProgramDataProgram {87440A4C-1FE4-412E-80C3-74E4F97A31B4}ExtensionsSignal Integrity  
C:ProgramDataProgram {87440A4C-1FE4-412E-80C3-74E4F97A31B4}ExtensionsVcs_SVN_Unicode 
C:ProgramDataProgram {87440A4C-1FE4-412E-80C3-74E4F97A31B4}ExtensionsMixed Simulation 
C:ProgramDataProgram {87440A4C-1FE4-412E-80C3-74E4F97A31B4}ExtensionsSIMetrix
$fileName = "C:empExtensionsExtensionsRegistry.xml"
$xml = [System.Xml.XmlDocument](Get-Content $fileName)

$Xml.Extensions.Item.Path.ForEach{ $_ -replace 'Program  {87440A4C-1FE4-412E-80C3-74E4F97A31B4}', "Program {BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}"}

$Xml.Save($fileName)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

  • The -replace operator doesn't modify its LHS in place, it returns a modified copy of the LHS.

  • If the Path elements only have text content, using PowerShell's adaptation of the XML via dot notation returns just that text itself, not the element objects, so you cannot modify the elements that way.

Therefore, you must enumerate the Path elements differently and assign the result of the
-replace operations back to their .InnerText property:

$xml.Extensions.Item.ChildNodes.Where({ $_.Name -eq 'Path' }).ForEach({ 
  $_.InnerText = $_.InnerText -replace 'Program  {87440A4C-1FE4-412E-80C3-74E4F97A31B4}', 'Program {BBB7C1EB-B0B0-40F3-B1D0-1F28111C5806}'
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...