0

I have an PSCustomObject, I want to convert to xml using powershell. When I convert using ConvertTo-Xml, I am using following command to convert

$test = ConvertTo-Xml -As String -NoTypeInformation -InputObject $data

It is converting to xml in below format.

<?xml version="1.0" encoding="utf-8"?>
<Objects>
   <Object>
      <Property Name="ABC">1</Property>
      <Property Name="PQR">2</Property>      
      <Property Name="XYZ">3</Property>
   </Object>
</Objects>

whereas I want to be in below format.

<?xml version="1.0" encoding="utf-8"?>
<Objects>
   <Object>
      <ABC>1</ABC>
      <PQR>2</PQR>
      <XYZ>3</XYZ>
   </Object>
</Objects>

How can I do this?

Prasad Gavande
  • 213
  • 1
  • 4
  • 19

2 Answers2

0

You could use xsl for this. See this answer how to use xsl in powershell

And this xsl would do the job:

<xsl:stylesheet version="1.0" 
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

  <xsl:strip-space elements="*"/>  

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>
  
  <xsl:template match="Property">
    <xsl:element name="{@Name}">
      <xsl:value-of select="text()"/>
    </xsl:element>
  </xsl:template>
    
</xsl:stylesheet>
Siebe Jongebloed
  • 3,906
  • 2
  • 14
  • 19
0

Use Xml Linq with Powershell

using assembly System.Xml.Linq
$inputFilename = "c:\temp\test.xml"
$outputFilename = "c:\temp\test1.xml"

$doc = [System.Xml.Linq.XDocument]::Load($inputFilename)

$object = $doc.Descendants("Object")[0]
$properties = $object.Elements()
$Object.RemoveNodes()

foreach($property in $properties)
{
   $name = $property.Attribute("Name").Value
   $value = $property.Value
   $newElement = [System.Xml.Linq.XElement]::new([System.Xml.Linq.XName]::Get($name),$value);
   $object.Add($newElement)
}
$doc.Save($outputFilename)
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • 1
    You can use the $test string in above by changing the Load method to Parse : $doc = [System.Xml.Linq.XDocument]::Parse($test) – jdweng Jul 13 '23 at 14:15