find string and replace it XML file

Welcome Forums General PowerShell Q&A find string and replace it XML file

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 7 years ago.

  • Author
  • #5450

    Points: 0
    Rank: Member

    by fazlook at 2013-01-17 13:46:35


    I need to find some strings in XML file and replace them with empty "" string. How can I do that and save back the file ?

    Need to find c/o and replace it with ""

    I have this so far :

    $xml = [xml](Get-Content "c:\1.xml")

    $Contract = $xml.T550.specimen.contract
    $annuitantLastName = $Contract[0].annuitantLastName
    if ($annuitantLastName -match "c/o")

    here need to replace then save


    example of contract field:

    contractNumber : 2
    annuitantSIN : 1111111
    annuitantSalutation :
    annuitantFirstName : c/oDenise
    annuitantLastName : whatever
    annuitantAddress1 : 535 c/oBoul whatever
    annuitantAddress2 : This That
    annuitantCity : ummmm
    annuitantProvince : USc/0
    annuitantPostalCode : j4534

    by DonJ at 2013-01-17 15:37:39

    The XML object will have a Save() method. See ... ve(v=vs.80).aspx

    by fazlook at 2013-01-18 05:51:15

    But how can I replace a string inside a big string ? I used -replace but did not save the result back to my file

    by DonJ at 2013-01-18 06:18:21

    When you cast something as [xml], it isn't a big string. You'll need to use the methods of the XMLDocument class to obtain the node you're after and change its value. You won't use -replace. So something like $Contract[0].annuitantLastName = 'new value'.

    by fazlook at 2013-01-18 06:54:04

    Hi Don, I dont want to replace a value , I just want to delete strings like c/o or d/y ....stuff like that......

    I did rename my xml file as .txt and the following worked :
    ($xm = Get-Content "g:\1.xml.txt") | Foreach-Object {
    $_ -replace "c/o","" `
    -replace "&",""
    } | Set-Content 'g:\1.txt'

    but when I name it back to 1.xml it wont load ............

    by DonJ at 2013-01-18 07:37:03

    So, you're replacing & with a blank. The ampersand is used within XML to escape illegal characters, so it's possible that in removing the & you've broken the XML. Without seeing the entire original XML (please don't post it here, though) I couldn't tell you if that was the case or not.

The topic ‘find string and replace it XML file’ is closed to new replies.