如何在 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** 输出时,
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
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
广告