Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

Save XML file after changes in powershell

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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}'
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...