将多个XML转换为JSON列表 [英] Convert multiple XMLs to JSON list

查看:501
本文介绍了将多个XML转换为JSON列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PowerShell脚本将具有相同XML属性格式的多个XML文件转换为JSON文件.这个想法是创建一个JSON列表,其中每个项目都是XML文件的JSON表示形式.可以吗?输入和输出的示例:

I want to convert multiple XML files with the same XML attribute format to a JSON file using a PowerShell script. The idea is to create a JSON list with each item being the JSON representation of the XML file. Is it doable? An example of input and output:

输入:

File1.xml:

<File>
<Child1> First xml child 1</Child1>
<Child2>First xml child 2</Child2>
</File>

File2.xml:

<File>
<Child1> Second xml child 1</Child1>
<Child2>Second xml child 2</Child2>
</File>

输出:

[
  {
    File: [
      {Child1 : First xml child 1 },
      { Child2: First xml child 2}
    ]
  },
  {
    File: [
      {Child1 : Second xml child 1 },
      { Child2: Second xml child 2}
    ]
  }
]

推荐答案

以下使用帮助器功能ConvertFrom-Xml仅非常简单的XML文档(例如样本文档)转换为嵌套的哈希表带有有序键的键,然后可以使用ConvertTo-Json将其转换为JSON:

The following uses a helper function, ConvertFrom-Xml, to convert only very simple XML documents such as your sample documents to nested hashtables with ordered keys, which can then be converted to JSON with ConvertTo-Json:

# Helper function that converts a *simple* XML document to a nested hashtable
# with ordered keys.
function ConvertFrom-Xml {
  param([parameter(Mandatory, ValueFromPipeline)] [System.Xml.XmlNode] $node)
  process {
    if ($node.DocumentElement) { $node = $node.DocumentElement }
    $oht = [ordered] @{}
    $name = $node.Name
    if ($node.FirstChild -is [system.xml.xmltext]) {
      $oht.$name = $node.FirstChild.InnerText
    } else {
      $oht.$name = New-Object System.Collections.ArrayList 
      foreach ($child in $node.ChildNodes) {
        $null = $oht.$name.Add((ConvertFrom-Xml $child))
      }
    }
    $oht
  }
}

[xml[]] (Get-Content -Raw file[12].xml) | ConvertFrom-Xml | ConvertTo-Json -Depth 3

使用示例文件,结果如下:

With your sample files, this yields:

[
    {
        "File":  [
                     {
                         "Child1":  " First xml child 1"
                     },
                     {
                         "Child2":  "First xml child 2"
                     }
                 ]
    },
    {
        "File":  [
                     {
                         "Child1":  " Second xml child 1"
                     },
                     {
                         "Child2":  "Second xml child 2"
                     }
                 ]
    }
]

这篇关于将多个XML转换为JSON列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆