I am reading the content of an xml file in PowerShell and changing it's version number(from 1.1 to 1.0) before casting it to xml so that it doesn't throw an exception, because as I have learned version 1.1 is not supported.
Then I make some changes to the content and I want to save it to a file but change the version again from 1.0 to 1.1 like it was when I read it.
Here are the commands I use:
@'
<?xml version='1.1' encoding='UTF-8'?>
<Root>
<element1>
<string>name</string>
</element1>
<version>3.2.1</version>
</Root>
'@ | Out-File Demo.xml
$content = (Get-Content .\Demo.xml)
$replacedVersion = $content.Replace('<?xml version=''1.1'' encoding=''UTF-8''?>','<?xml version=''1.0'' encoding=''UTF-8''?>')
$XMLFile = [xml]$replacedVersion
// here I make my changes
// ...
$pathToSaveAt = "C:\MyDir\newFile.xml"
$XMLFile.Save($pathToSaveAt)
But the result I get is an xml file with a header containing version
<?xml version="1.0" encoding="UTF-8" ?>
I want it to be version 1.1.
The result I am trying to get is an xml file with the contents:
<?xml version='1.1' encoding='UTF-8'?>
<Root>
// all the changes I made
</Root>
How can I achieve that?
Does this help you?
@'
<?xml version='1.1' encoding='UTF-8'?>
<Root>
<element1>
<string>name</string>
</element1>
<version>3.2.1</version>
</Root>
'@ | Out-File Demo.xml
$newContent = @()
$content = (Get-Content .\Demo.xml)
ForEach($Regel In $content){
if($Regel -match "<?xml*"){
$newContent +=$Regel
$newContent +=""
}
elseif ($Regel -match "<root>"){
$newContent += "<Root>"}
elseif ($Regel -match "</Root>"){
$newContent += "</Root>"
}
elseif (($Regel -match "<elem*")-or ($Regel -match "<version>3.*")){
$newContent += ' //test me'
}
}
$newContent |Out-File Cdemo.xml
out file is
<?xml version='1.1' encoding='UTF-8'?>
<Root>
//test me
//test me
</Root>