如何在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
获取特定的属性,例如名称,类型等。
$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
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短