Edit .XML file using Powershell encoding

I need to edit the .xml file using powershell. What I need to do is download the XML file from the server, update the version number and save it on the local computer. This is what I did.

[xml]$myXML = get-content $xmlFileServer $myXML.'ivy-module'.info.revision = $newVersion $myXML.Save($newXMLFileName) 

Then I will have a new xml file on my local computer. However, I doubt the encoding is different since I cannot process this .xml file. The XML I should get looks something like this:

 <?xml version="1.0" encoding="UTF-8"?> <ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd" xmlns:e="http://ant.apache.org/ivy/extra"> <info organisation="XXXX" module="XXXX" revision="2.0.1.0" status="release" publication="20131119202217" /> <publications> <artifact name="XXXX" type="dll" ext="zip" conf="*" /> </publications> </ivy-module> 

However, after editing with powershell, .xml contains some hidden information. I tried to open with NotePad ++, I got something like this:

 <?xml version="1.0" encoding="UTF-8"?> <ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd" xmlns:e="http://ant.apache.org/ivy/extra"> <info organisation="XXXX" module="XXXX" revision="2.0.1.0" status="release" publication="20131119202217"/> <publications> <artifact name="XXXX" type="dll" ext="zip" conf="*"/> </publications> </ivy-module> 

Can someone tell me why the situation? Thank you very much.

+6
source share
3 answers

"Γ―" ΒΏ"is " Byte Estimation " for UTF-8. There is a solution for writing a UTF-8 file without a specification: Use PowerShell to write a file in UTF-8 without a specification

0
source

This works for me based on the link above and on this blog post

 $enc = New-Object System.Text.UTF8Encoding( $false ) $wrt = New-Object System.XML.XMLTextWriter( 'c:\path\out.xml', $enc ) $wrt.Formatting = 'Indented' $myXML.Save( $wrt ) $wrt.Close() 

Indentation is a personal taste; I prefer my XML to be readable. Requires $ wrt.Close ().

+6
source

Instead of reading xml using get-content, read xml directly with XmlDocument:

function test ($ path) {

 $xDoc = New-Object System.Xml.XmlDocument $file = Resolve-Path($path) $xDoc.Load($file) $xDoc.Save($file) #will save correctly 

}

+1
source

Source: https://habr.com/ru/post/958498/


All Articles