如何在 PowerShell 中将 XML 转换为 JSON
-
使用
XPath 选择
、哈希表
和ConvertTo-Json
在 PowerShell 中将 XML 转换为 JSON -
使用
ConvertTo-Json
和ConvertFrom-Xml
cmdlet 在 PowerShell 中将 XML 转换为 JSON - 结论

本综合指南深入探讨了使用 PowerShell 这一强大脚本语言和命令行外壳将 XML 文档转换为 JSON 格式字符串的过程。XML 和 JSON 格式在数据交换和存储中具有基础性作用,尤其在配置和数据处理至关重要的环境中。
PowerShell 凭借其强大的 cmdlet 集合简化了这一转换过程。本指南探讨了两种主要方法:第一种方法涉及 XPath 选择
、哈希表
和 ConvertTo-Json
的组合,第二种方法利用 ConvertTo-Json
和 ConvertFrom-Xml
cmdlet。
该指南提供了逐步的方法,从访问 XML 文档的键和值开始,构建一个用于存储数据的 PowerShell 哈希,最后将哈希转换为 JSON。每种方法都通过详细的示例和语法进行说明,确保对涉及的过程有清晰的理解。
使用 XPath 选择
、哈希表
和 ConvertTo-Json
在 PowerShell 中将 XML 转换为 JSON
访问 XML 文档的键和值
PowerShell 允许使用 Select-Xml
cmdlet 操作 XML 文档节点。我们可以指定 XPath
表达式来查找 XML 文档中的节点及其文本值。
语法:
Select-Xml
[-XPath] <string>
[-Path] <string[]>
[-Namespace <hashtable>]
[<CommonParameters>]
让我们创建一个名为 employeeinfo.xml
的 XML 文档,内容如下。
XML - employeeinfo.xml
:
<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee>
<EmpId>1</EmpId>
<EmpAge>45</EmpAge>
<EmpDesignation>SSE</EmpDesignation>
</Employee>
<Employee>
<EmpId>2</EmpId>
<EmpAge>34</EmpAge>
<EmpDesignation>Junior SE</EmpDesignation>
</Employee>
</Employees>
现在,我们将使用 Select-Xml
cmdlet 访问每个 XML 节点 EmpId
、EmpAge
和 EmpDesignation
,如下所示。
代码:
$empIds = Select-Xml -Path "D:\codes\employeeinfo.xml" -XPath "//Employee//EmpId" | foreach { $_.node.InnerText }
$empAges = Select-Xml -Path "D:\codes\employeeinfo.xml" -XPath "//Employee//EmpAge" | foreach { $_.node.InnerText }
$empDesigs = Select-Xml -Path "D:\codes\employeeinfo.xml" -XPath "//Employee//EmpDesignation" | foreach { $_.node.InnerText }
在这个示例中,-Path
是 employeeinfo.xml
所在的位置。由于我们需要为每个员工对象获取三个节点,因此使用了 PowerShell foreach
。
每个节点的 XPath
表达式看起来如下。EmpID
节点可以通过 XPath
查询"//Employee//EmpId"
访问。
EmpAge
节点可以通过 XPath
查询"//Employee//EmpIAge"
访问。EmpDesignation
节点可以通过 XPath
查询"//Employee//EmpDesignation"
访问。
引用变量 $empIds
、$empAges
和 $empDesigs
分别包含相关 XML 节点的值数组。让我们将数组写入 PowerShell 控制台窗口。
构建 PowerShell 哈希以存储数据
我们没有直接的方法将 XML 文档转换为 JSON 字符串。因此,如上节所示,我们必须提取 XML 数据并将这些数据推送到 PowerShell 哈希中作为中间格式。
让我们构建哈希。
$empObjHash1 = @{
EmpId = $empIds[0];
EmpAge = $empAges[0];
EmpDesignation = $empDesigs[0];
}
$empObjHash2 = @{
EmpId = $empIds[1];
EmpAge = $empAges[1];
EmpDesignation = $empDesigs[1];
}
$finalHash = @{}
$finalHash.Add("emp1", $empObjHash1)
$finalHash.Add("emp2", $empObjHash2)
我们从 XML 中提取了两个员工对象以作演示,并将这些数据推送到两个哈希对象 $empObjHash1
和 $empObjHash2
中。然后,通过将两个员工对象推送到 $finalHash
中创建该哈希。
如果我们打印 $finalHash
,它将如下所示。
我们可以使用 foreach
循环更详细地检查 $finalHash
。
代码:
foreach ($em in $finalHash.keys) {
foreach ($emp in $finalHash[$em]) {
foreach ($val in $emp.keys) {
Write-Host "Key:" $val "Value:" $emp[$val]
}
}
}
输出:
$finalHash
已构建完成,并从 XML 中提取了相关数据。
将哈希转换为 JSON
既然我们得到了 PowerShell 哈希 $finalHash
,就可以使用 ConvertTo-Json
cmdlet 从哈希创建 JSON。
语法:
ConvertTo-Json
[-InputObject] <Object>
[-Depth <Int32>]
[-Compress]
[-EnumsAsStrings]
[-AsArray]
[-EscapeHandling <StringEscapeHandling>]
[<CommonParameters>]
让我们传递创建的哈希 $finalHash
以创建 JSON 字符串,如下所示。
代码:
$finalHash | ConvertTo-Json
输出:
PowerShell 完整脚本:
$empIds = Select-Xml -Path "D:\codes\employeeinfo.xml" -XPath "//Employee//EmpId" | foreach { $_.node.InnerText }
$empAges = Select-Xml -Path "D:\codes\employeeinfo.xml" -XPath "//Employee//EmpAge" | foreach { $_.node.InnerText }
$empDesigs = Select-Xml -Path "D:\codes\employeeinfo.xml" -XPath "//Employee//EmpDesignation" | foreach { $_.node.InnerText }
$empObjHash1 = @{
EmpId = $empIds[0];
EmpAge = $empAges[0];
EmpDesignation = $empDesigs[0];
}
$empObjHash2 = @{
EmpId = $empIds[1];
EmpAge = $empAges[1];
EmpDesignation = $empDesigs[1];
}
$finalHash = @{}
$finalHash.Add("emp1", $empObjHash1)
$finalHash.Add("emp2", $empObjHash2)
foreach ($em in $finalHash.keys) {
foreach ($emp in $finalHash[$em]) {
foreach ($val in $emp.keys) {
Write-Host "Key:" $val "Value:" $emp[$val]
}
}
}
$finalHash | ConvertTo-Json
使用 ConvertTo-Json
和 ConvertFrom-Xml
cmdlet 在 PowerShell 中将 XML 转换为 JSON
在 PowerShell 中,将数据从 XML 转换为 JSON 格式是一个常见的需求,特别是在与 Web API 或现代 Web 服务接口时。PowerShell 通过其 ConvertTo-Json
和 ConvertFrom-Xml
cmdlet 简化了这一任务。
语法:
-
Get-Content
:从文件读取内容。-Path <String>
:指定文件的路径。
-
ConvertTo-Json
:将对象转换为 JSON 格式字符串。-InputObject <Object>
:指定要转换的对象。-Depth <Int32>
:指定要包含的对象层级深度。
示例
# Path to the XML file
$xmlFilePath = "employeeinfo.xml"
# Read the content of the XML file and convert to XML object
$xml = New-Object XML
$xml.Load($xmlFilePath)
# Parse the XML and create an object array
$employeeArray = @()
foreach ($employee in $xml.Employees.Employee) {
$empObject = [PSCustomObject]@{
EmpId = $employee.EmpId
EmpAge = $employee.EmpAge
EmpDesignation = $employee.EmpDesignation
}
$employeeArray += $empObject
}
# Convert the array to JSON
$json = $employeeArray | ConvertTo-Json
# Display the result
Write-Output $json
在我们的脚本中,我们首先使用变量 $xmlFilePath
指定 XML 文件的路径。使用 Get-Content
,我们将此文件的内容读入变量 $xmlContent
。
然后将此内容强制转换为 [xml]
类型,创建一个结构化的 XML 对象($xmlObject
)。该对象被传递给 ConvertTo-Json
以执行转换为 JSON 格式。
最后,我们使用 Write-Output
打印 JSON 字符串。
输出:
结论
总之,本指南成功演示了使用 PowerShell 将 XML 文档转换为 JSON 字符串的实用和高效方法。通过展示两种不同的方法 - 一种是将 XML 数据提取到 PowerShell 哈希中,另一种是利用 ConvertFrom-Xml
cmdlet - 本指南提供了多样的选项,以满足不同用户的需求和场景。
逐步的说明,加上相关的代码片段和输出,使读者能够轻松理解这一概念并将这些方法应用于现实世界的情况。PowerShell 在处理和转换数据格式方面的灵活性和强大功能显而易见,使其成为处理 XML 和 JSON 数据转换的管理员和开发人员不可或缺的工具。
Nimesha is a Full-stack Software Engineer for more than five years, he loves technology, as technology has the power to solve our many problems within just a minute. He have been contributing to various projects over the last 5+ years and working with almost all the so-called 03 tiers(DB, M-Tier, and Client). Recently, he has started working with DevOps technologies such as Azure administration, Kubernetes, Terraform automation, and Bash scripting as well.