powershell xml 到 json 空白文件

powershell xml to json blank file

我正在尝试使用 powershell 将 xml 文件转换为 json。 在那之前它非常简单,但是源文件在我看来编码错误并且当我应用 convertto-json 时,结构 json 是空的:

XML 来源:

<?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>

和Json输出:

[
    [

    ],
    [
        [
            [
                [
                    [

                    ],
                    [

                    ]
                ]
            ],
            [
                [
                    [

                    ],
                    [

                    ],
                    [

                    ],
                    [

                    ],
                    [

                    ],
                    [

                    ],

我的转换代码:

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

遗憾的是,这并不容易。

看看这个 GitHub Repo 我以前用它来完全按照你的要求做。

您的代码将更改为:

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

使用这种方法确实给我带来了很多"whitespace"噪音。

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

通过这种方式重新编译 XML 文件确实删除了空格并创建了一个整洁的对象。

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