xml - 确定 XML 节点存在

标签 xml powershell powershell-2.0

这可能很简单,但我试图确定一个节点是否存在于 XML 文档中。我以为我在这篇文章中找到了答案, How to check whether a node exists or not using powershell without getting exception? ,但我没有让它工作。这是我最近的尝试。

foreach ($vendor in $xml.Vendors.Vendor| Where-Object  {$_.Type -match "Send"}) {
    $NodeExists = $vendor.SelectSingleNode($vendor.EncKey)
    if ($NodeExists -ne $null) {
        # Do something
    }
    else {
       # something else
    }
   }

如有任何帮助,我们将不胜感激。

编辑:这是我的测试文件中的 XML。我需要找出每个供应商的 EncKey 是否存在或注释。

<?xml version="1.0" encoding="UTF-8"?>
    <!-- Vendors we will send and retreive files from Get-Send means we will get a file and send them a file Send means we will only send them a file-->
    <Vendors>
        <Vendor Type="Get-Send">
            <Name>Vendor1</Name>            
            <RemotePath>/Remote/Path1/</RemotePath>
            <EncKey>pgpenc.key</EncKey>
        </Vendor>
        <Vendor Type="Send">
            <Name>Vendor2</Name>            
            <RemotePath>/Remote/Path2/</RemotePath> 
            <!-- This one has no EncKey -->         
        </Vendor>
    </Vendors>

最佳答案

我能想到的最简单的方法是尝试将节点值写入变量,然后查看该变量是否为空。这是标准书店 xml 文件的示例。

[xml]$bookstore = Get-Content .\bookstore.xml
foreach ($book in $bookstore.bookstore.book | Where-Object {$_.Type -match "novel"}) {
 $NodeExists = $book.author
 if($NodeExists){
  Write-Host $book.author
 }
 else{
  Write-Host 'No Author'
 }
} 

所以对于你的脚本,我认为它可能是

$NodeExists = $null
foreach ($vendor in $xml.Vendors.Vendor| Where-Object  {$_.Type -match "Send"}) {
 $NodeExists = $vendor.EncKey
 if ($NodeExists) {
  # Do something
 }
 else {
  # something else
  }
}

关于xml - 确定 XML 节点存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20433932/

相关文章:

powershell - 使用 powershell 替换链接中的字符

powershell - 从字符串行中删除空格并将其用于数组

c# - XmlNode.SelectSingleNode 返回当前元素之外的元素?

jquery - 按父 ID 将 xml 分组为 ul li html

java - Jackson XmlMapper.config() 不起作用

powershell - 构建 IP 地址列表

powershell - 使用 Azure 资源管理器时如何获取 CustomScriptExtensions 的输出?

sorting - "MMdd"中的昨天日期,具体的输出文件夹选择取决于日期

Powershell Write-EventLog/Get-WinEvent 消息问题

Android: ListView 的布局问题