Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit .XML file with Powershell, encoding

Tags:

powershell

xml

I need to edit a .xml file with powershell. The thing I need to do is to download the .xml file from the server, updated the version number, and then save it in my 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 in my local computer. However, I doubt the coding is different since I can't process with this .xml file. The .xml I should get is 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, the .xml contains some hidden info. 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 anyone tell me why is the situation? Thank you so much.

like image 373
Payson Avatar asked Nov 20 '13 17:11

Payson


2 Answers

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()

The 'Indented' setting is personal taste; I prefer my XML human readable. The $wrt.Close() is also required.

like image 160
SimonSC Avatar answered Oct 23 '22 11:10

SimonSC


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

function test($path) {

$xDoc = New-Object System.Xml.XmlDocument
$file = Resolve-Path($path)

$xDoc.Load($file)
$xDoc.Save($file) #will save correctly

}

like image 32
Patrice Calvé Avatar answered Oct 23 '22 09:10

Patrice Calvé