如何在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
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿