如何来从XML使用PowerShell的属性值?(How to fetch an attribute

2019-06-27 14:55发布

我有一个XML文件,从中我得到一个特定的行后的字符串列表。

在文件中,我需要寻找一个标签Event ,并获得属性值DLLRoutine 。 例如,标签将类似于下面...

<Event Definition="Validate" DLLPath="" DLLName="Helper.dll" DLLClass="HelpMain" 
       DLLRoutine="pgFeatureInfoOnValidate_WriteToRegSelectedFeatures" 
       InputParameters="pTreeViewFeatureTreeServerOS" RunOnce="no"/>

我只需要得到Dllroutine值。 如何使用PowerShell来做到这一点?

Answer 1:

假设你的XML结构是类似的东西:

$xml = [xml]'
<Events>
<Event Definition="Validate" DLLPath="" DLLName="Helper.dll" DLLClass="HelpMain" DLLRoutine="pgFeatureInfoOnValidate_WriteToRegSelectedFeatures" InputParameters="pTreeViewFeatureTreeServerOS" RunOnce="no"/>
<Event Definition="Validate1" DLLPath="" DLLName="Helper.dll1" DLLClass="HelpMain1" DLLRoutine="pgFeatureInfoOnValidate_WriteToRegSelectedFeatures" InputParameters="pTreeViewFeatureTreeServerOS" RunOnce="no"/>
</Events>
'

#Or get it from a XML file
$xml = [xml](Get-Content $XMLPath)

$xml.Events.Event | Select DLLName


Answer 2:

假设你的Event元素都有一个Events元素根:

$xml.Events.Event.DLLName

我只在PowerShell中测试这3



Answer 3:

你也可以使用XPath,而不是点符号:

$xml.SelectNodes('//Events/Event') | select DLLName


Answer 4:

为什么不Select-XML

$xml = [xml]'
<Events>
<Event Definition="Validate" DLLPath="" DLLName="Helper.dll" DLLClass="HelpMain" DLLRoutine="pgFeatureInfoOnValidate_WriteToRegSelectedFeatures" InputParameters="pTreeViewFeatureTreeServerOS" RunOnce="no"/>
<Event Definition="Validate1" DLLPath="" DLLName="Helper.dll1" DLLClass="HelpMain1" DLLRoutine="pgFeatureInfoOnValidate_WriteToRegSelectedFeatures" InputParameters="pTreeViewFeatureTreeServerOS" RunOnce="no"/>
</Events>
'

Select-XML -xml $xml -xpath "//Event/@DllName"


Answer 5:

尝试$xml.Events.Event.DLLName

这将在第2版的工作,我已经试过几个脚本中使用XPath和它没有忘记,直到我尝试了点符号我想我这样做是错误的时间。



文章来源: How to fetch an attribute value from xml using powershell?