使用powershell解析xml [英] Parsing xml using powershell
问题描述
我是 PowerShell 的新手.我有一个配置 XML 读取为 -
I am new to powershell. I have a config XML which reads as -
<xml>
<Section name="BackendStatus">
<BEName BE="crust" Status="1" />
<BEName BE="pizza" Status="1" />
<BEName BE="pie" Status="1" />
<BEName BE="bread" Status="1" />
<BEName BE="Kulcha" Status="1" />
<BEName BE="kulfi" Status="1" />
<BEName BE="cheese" Status="1" />
</Section>
</xml>
我需要解析 BEName
中的每个元素来检查状态.如何使用 PowerShell 完成此操作?
I need to parse each element in BEName
to check Status. How can this be done using PowerShell?
推荐答案
第一步是将您的 xml 字符串加载到 XmlDocument 中,使用 powershell 的将字符串转换为 [xml] 的独特能力
First step is to load your xml string into an XmlDocument, using powershell's unique ability to cast strings to [xml]
$doc = [xml]@'
<xml>
<Section name="BackendStatus">
<BEName BE="crust" Status="1" />
<BEName BE="pizza" Status="1" />
<BEName BE="pie" Status="1" />
<BEName BE="bread" Status="1" />
<BEName BE="Kulcha" Status="1" />
<BEName BE="kulfi" Status="1" />
<BEName BE="cheese" Status="1" />
</Section>
</xml>
'@
Powershell 使解析带有点符号的 xml 变得非常容易.这语句将为您的 BEName 元素生成一系列 XmlElements:
Powershell makes it really easy to parse xml with the dot notation. This statement will produce a sequence of XmlElements for your BEName elements:
$doc.xml.Section.BEName
然后您可以将这些对象通过管道传输到 where-object cmdlet 中以过滤掉结果.您可以使用 ?作为哪里的快捷方式
Then you can pipe these objects into the where-object cmdlet to filter down the results. You can use ? as a shortcut for where
$doc.xml.Section.BEName | ? { $_.Status -eq 1 }
大括号内的表达式将针对每个 XmlElement 中的管道,只有那些状态为 1 的才会被返回.$_运算符引用管道中的当前对象(一个 XmlElement).
The expression inside the braces will be evaluated for each XmlElement in the pipeline, and only those that have a Status of 1 will be returned. The $_ operator refers to the current object in the pipeline (an XmlElement).
如果你需要为管道中的每个对象做一些事情,你可以通过管道对象进入 foreach-object cmdlet,它为每个对象执行一个块在管线中.% 是 foreach 的快捷方式:
If you need to do something for every object in your pipeline, you can pipe the objects into the foreach-object cmdlet, which executes a block for every object in the pipeline. % is a shortcut for foreach:
$doc.xml.Section.BEName | ? { $_.Status -eq 1 } | % { $_.BE + " is delicious" }
Powershell 在这方面做得很好.组装管道真的很容易对象,过滤管道,并对管道中的每个对象进行操作.
Powershell is great at this stuff. It's really easy to assemble pipelines of objects, filter pipelines, and do operations on each object in the pipeline.
这篇关于使用powershell解析xml的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!