0

As part of a larger PowerShell Script, I'm trying to replace two lines within an xml file:

<!--Some description text here-->
<Variable></Variable>

I've been able to replace the text when it's on a single line however I've not been able to find a way to remove new lines from the file.

The obvious thought would be to try to use \r\n but this doesn't work eg:

$XML = Get-Content "Config.xml"
$Pattern = '\r\n'
$Replacement = ""
$NewXML = $XML -replace $Pattern, $Replacement
$NewXML | Set-Content -Path "Config.xml"

I'd expect the above to remove all line breaks in the file but it does nothing.

  • 3
    Powershell supports XML right out of the box, so why not edit the document as one edits an XML document? – vonPryz Jul 15 '23 at 06:28
  • @vonPryz I need the script to edit the xml, not manually edit it. – Shupershuff Jul 15 '23 at 07:23
  • I don't think regex works for new lines as such I've found a workaround: ```$XML = Get-Content "Config.xml" $Pattern = ";;\t;;\t.*?;;" $NewXML = [string]::join(";;",($xml.Split(" `r `n"))) $NewXML = $NewXML -replace $Pattern, "" $NewXML = $NewXML -replace ";;"," `r `n" $NewXML | Set-Content -Path "Config.xml"``` Apologies for formatting. Stackoverflow markdown guide states that adding two spaces after each line adds a linebreak but that's obviously false. – Shupershuff Jul 15 '23 at 07:25
  • This question is relevant. https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags https://www.educba.com/powershell-xml/ - this is a good demo. I'd be looking at the xpath option – GregHNZ Jul 15 '23 at 07:54
  • 4
    Edit the XML document as an _XML object_, not as _text_. Then you can use XMLDocument's `.RemoveChild()` and other methods that understand the XML structure. – vonPryz Jul 15 '23 at 07:58
  • Do you only want to remove the `` node when it's empty (eg. it doesn't have any child nodes)? Or do you want to remove all `` nodes and their descendants? – Mathias R. Jessen Jul 15 '23 at 13:27

0 Answers0