如何在 PowerShell 中將 XML 轉換為 JSON
-
使用
XPath 選擇
、哈希表
和ConvertTo-Json
在 PowerShell 中將 XML 轉換為 JSON -
使用
ConvertTo-Json
和ConvertFrom-Xml
Cmdlet 在 PowerShell 中將 XML 轉換為 JSON - 結論

本綜合指南深入探討使用 PowerShell 將 XML 文檔轉換為 JSON 格式字串的過程,PowerShell 是一種強大的腳本語言和命令列外殼。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.