Home > Software design >  PowerShell .Save($path) changing formatting of xml file
PowerShell .Save($path) changing formatting of xml file

Time:10-20

how to save the xml file modified by the script so that my formatting remains there?

Original pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>ArtifactParent</artifactId>
        <groupId>MaxGroup</groupId>
        <version>2.3.0</version>
    </parent>

   <artifactId>Artefact</artifactId>
   <version>1.2.3-SNAPSHOT</version>
   <packaging>pom</packaging>
   <name>This is my name</name>

   <modules>
       <module>Module1</module>
       <module>Module2</module>
   </modules>

   <dependencyManagement>
       <dependencies>
           <dependency>
               <groupId>javax</groupId>
               <artifactId>javaee-api</artifactId>
               <version>${javaee.version}</version>
               <scope>provided</scope>
           </dependency>
       </dependencies>
   </dependencyManagement>

</project>

Purpose of script is change specific version of parent to new version. PowerShell script :

$xmlDoc = [xml] Get-Content $xmlFileName

do-something

$xmlDoc.Save($file)

When I use this script, it delete all tabulators and new-lines.

New pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <artifactId>ArtifactParent</artifactId>
    <groupId>MaxGroup</groupId>
    <version>2.3.0</version>
  </parent>
  <artifactId>Artefact</artifactId>
  <version>1.2.3-SNAPSHOT</version>
  <packaging>pom</packaging>
  <name>This is my name</name>
  <modules>
    <module>Module1</module>
    <module>Module2</module>
  </modules>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>${javaee.version}</version>
        <scope>provided</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
</project>

Can you please advise me some solution which keep my formatting and also change version of parent.

CodePudding user response:

To prevent .Net's XML library about re-formatting the file, one needs to first tell XML Document not to mess with whitespace. This is done via creating a XmlDocument object, setting PreserveWhitespace as true and then loading the document content into it. Like so,

$xmlDoc = new-object xml.xmldocument                             
$xmlDoc.PreserveWhitespace = $true                               
$xmlDoc.Load($xmlFileName)
  • Related