如何在 PowerShell 中讀取 XML 檔案?
在 PowerShell 中讀取 XML 檔案非常簡單。我們以下面的 XML 檔案為例:
示例
<Animals> <Animal Name="Elephant" Type="Wild"> <Residence>Forest</Residence> <Color>Brown</Color> </Animal> <Animal Name="Dog" Type="Pet"> <Residence>Street</Residence> <color>Multi</color> </Animal> <Animal Name="Tiger" Type="Wild"> <Residence>Forest</Residence> <color>Yellow</color> </Animal> </Animals>
假設此檔案儲存在我們當前路徑下的 **Animals.xml** 中,要讀取此 XML 檔案,我們首先使用 **Get-Content** 命令獲取檔案內容,然後將其轉換為 XML 型別。例如:
示例
[XML]$xmlfile = Get-Content .\Animals.xml
當您檢查 **$xmlfile** 輸出時,
輸出
PS E:\scripts\Powershell> $xmlfile Animals ------- Animals
**Animals** 標籤在這裡稱為元素,要從元素中獲取屬性,我們需要使用該元素,例如:
示例
$xmlfile.Animals PS E:\scripts\Powershell> $xmlfile.Animals Animal ------ {Elephant, Dog, Tiger}
類似地,您可以使用 **Animal** 元素來擴充套件更多屬性,依此類推。例如:
示例
$xmlfile.Animals.Animal PS E:\scripts\Powershell> $xmlfile.Animals.Animal Name Type Residence Color ---- ---- --------- ----- Elephant Wild Forest Brown Dog Pet Street Multi Tiger Wild Forest Yellow
要獲取特定屬性,例如 Name、Type 等。
$xmlfile.Animals.Animal.name
輸出
PS E:\scripts\Powershell> $xmlfile.Animals.Animal.name Elephant Dog Tiger
要獲取動物的型別。
$xmlfile.Animals.Animal.Type
輸出
PS E:\scripts\Powershell> $xmlfile.Animals.Animal.Type Wild Pet Wild
如果您希望將兩個或多個屬性一起以表格格式顯示,則可以使用 PowerShell 傳統 **Select 或 Format-Table** 命令。例如:
示例
$xmlfile.Animals.Animal | Select Name, Type
輸出
PS E:\scripts\Powershell> $xmlfile.Animals.Animal | Select Name, Type Name Type ---- ---- Elephant Wild Dog Pet Tiger Wild
廣告