Steven Poulain
Steven Poulain

Reputation: 53

powershell xml to json blank file

I'm trying to convert an xml file to json with powershell. Until then it is very simple, however the source file seems to me bad coded and when I apply convertto-json, the structure json is empty:

XML source :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PnCG3_configuration>
  <domains>
    <domain Name="xxxxx">
      <players>
        <player targetId="00-1c-e6-02-0a-00" targetIdType="mac" label="test" middlewareFamily="gekkota-3" />
        <player />
      </players>
    </domain>
    <domain Name="xxxxxxx2">
      <players>
        <player targetId="00-1c-e6-02-0a-00" targetIdType="mac" label="OfficeChateaugiron-TV01" middlewareFamily="gekkota-3" />
        <player targetId="00-1c-e6-02-20-00" targetIdType="mac" label="test-01" middlewareFamily="gekkota-3" />
        <player targetId="00-1c-e6-02-0b-00" targetIdType="mac" label="test-test-TV01" middlewareFamily="gekkota-3" />
        <player targetId="00-1c-e6-02-20-00" targetIdType="mac" label="test-TV01-test" middlewareFamily="gekkota-3" />
        <player targetId="00-1c-e6-02-20-00" targetIdType="mac" label="test" middlewareFamily="gekkota-3" />
        <player targetId="00-1c-e6-02-09-00" targetIdType="mac" label="test-test-TV01" middlewareFamily="gekkota-3" />
        <player targetId="00-1c-e6-02-04-00" targetIdType="mac" label="test-test-TV01" middlewareFamily="gekkota-3" />
        <player />
      </players>
    </domain>

And Json Out :

[
    [

    ],
    [
        [
            [
                [
                    [

                    ],
                    [

                    ]
                ]
            ],
            [
                [
                    [

                    ],
                    [

                    ],
                    [

                    ],
                    [

                    ],
                    [

                    ],
                    [

                    ],

My code for convert :

$xmlObject = [XML](Get-Content -Path $o)
$xmlObject | ConvertTo-JSON -depth 100 | Out-File "$o.json"

Upvotes: 5

Views: 985

Answers (2)

Rogier Langeveld
Rogier Langeveld

Reputation: 51

Using this method did create a lot of "whitespace" noise for me.

[Newtonsoft.Json.JsonConvert]::SerializeXmlNode($xmlObject) | Out-File "$o.json"

This way recompiling the XML file did remove the whitespace and created a neat object.

[Newtonsoft.Json.JsonConvert]::SerializeXmlNode([xml] $xmlObject.OuterXML ) | Out-File "$o.json"

Upvotes: 0

TobyU
TobyU

Reputation: 3908

Sadly it is not that easy.

Have a look at this GitHub Repo which I have used before to do exactly what you're asking for.

Your code would change to:

Add-Type -Path .\Newtonsoft.Json.dll
$xmlObject = [XML](Get-Content -Path $o)
[Newtonsoft.Json.JsonConvert]::SerializeXmlNode($xmlObject ) | Out-File "$o.json"

Upvotes: 4

Related Questions