简体   繁体   English

Powershell 从 xml 获取文本节点

[英]Powershell to get text nodes from xml

I am working on a simple powershell script that verify if inside of the xml file the attribute(s) exists.我正在编写一个简单的 powershell 脚本,用于验证 xml 文件中的属性是否存在。 The xml file looks like, xml文件看起来像,

<?xml version="1.0"?>
 <Objects>
  <Object>
   <Property Name="Browser">Firefox</Property>
   <Property Name="PDF">Adobe Reader</Property>
 </Object>
</Objects>

I want the powershell to verify if the attribute Firefox exists, and then to execute a task afterward.我希望 powershell 验证属性 Firefox 是否存在,然后执行任务。

[xml]$file = get-content C:\Admin\personalsettings.xml
$xmlProperties = $file.SelectNodes("/Objects/Object/Property")
Foreach ($xmlProperty in $xmlProperties) {
$strName = ($xmlProperty | Where-Object {$_.Name -eq "Firefox"    }).InnerXml
 If ($strName -eq "False")
 {
 Invoke-Item "C:\windows\protected\browser.exe"
 }
}

Note that Firefox is a child text node (the text content ) of a Property element in your XML, accessible via the latter's .InnerText property.请注意, Firefox是 XML 中Property元素子文本节点文本内容),可通过后者的.InnerText属性访问。

Therefore, you can retrieve the / test the existence of a Property element of interest as follows, using the Where() array method :因此,您可以使用Where()数组方法检索 / 测试感兴趣的Property元素的存在,如下所示:

$firefoxElem = $xmlProperties.Where({ $_.InnerText -eq 'FireFox' }, 'First')
$haveFirefoxElem = [bool] $firefoxElem

A simpler approach, if you only need to know the presence of the element of interest, is to use PowerShell's XML dot notation , which obviates the need for XPath expressions via .SelectNodes() :一种更简单的方法,如果您只需要知道感兴趣的元素的存在,是使用PowerShell 的 XML 点表示法,它不需要通过.SelectNodes()使用 XPath 表达式:

$haveFirefoxElem = $file.Objects.Object.Property.InnerText -contains 'FireFox'

Using xpath (case sensitive):使用 xpath(区分大小写):

if (select-xml "/Objects/Object/Property[text()='Firefox']" file.xml) { 'yes' } 
if (select-xml "//Property[text()='Firefox']" file.xml) { 'yes' } 
if (select-xml "//*[Property='Firefox']" file.xml) { 'yes' }
if (select-xml "*[Object[Property[@Name='Browser']='Firefox']]" file.xml) { 'yes' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM