powershell 基于节点值获取节点名称

wztqucjr  于 2023-06-23  发布在  Shell
关注(0)|答案(2)|浏览(175)

下面是XML

<?xml version="1.0" encoding="UTF-8"?>
<Configuration APIVersion="1905.1" IPS_CAT_VER="0">
    <Notificationlist transactionid="">
        <SendEmail>Enable</SendEmail>
        <SendSnmp>Disable</SendSnmp>
        <SignInEmail>Enable</SignInEmail>
        <SignInSnmp>Disable</SignInSnmp>
        <TooManyLoginEmail>Disable</TooManyLoginEmail>
        <TooManyLoginSnmp>Disable</TooManyLoginSnmp>
    </Notificationlist>
</Configuration>

我需要两个数组,一个带有Enable* Notificationlist,一个带有Disable**Notificationlist,就像

Enable        Disable
------        -------
SendEmail     SendSnmp
SignInEmail   SignInSnmp
              TooManyLoginEmail
              TooManyLoginSnmp

我试过

$xml = (Select-Xml -Path C:\Users\Lenovo\Desktop\shellscripts\xml\SNMP.xml -XPath '/Configuration/Notificationlist')
$nodes = $xml | ForEach-Object { $_.Node | select -ExpandProperty InnerText }

但它只给出节点值而不给出节点名称。

5f0d552i

5f0d552i1#

你可以使用下面的代码,它会给予你两个变量$Enabled$Disabled。要为启用值和禁用值的节点名称给予两个数组,请执行以下操作:

$Enabled = ($xml.Node | GM -MemberType Property | Select Name).Name | %{ if($xml.Node[$_].InnerText -eq "Enable") { $_ } }

$Disabled = ($xml.Node | GM -MemberType Property | Select Name).Name | %{ if($xml.Node[$_].InnerText -eq "Disable") { $_ } }
3phpmpom

3phpmpom2#

由于您希望执行两个不同的查询,我建议先加载XML一次,然后执行两个XPath查询。

$xml = [xml]::new(); $xml.Load("C:\Users\Lenovo\Desktop\shellscripts\xml\SNMP.xml")

$enableNames = $xml | Select-Xml -XPath '/Configuration/Notificationlist/*[text()="Enable"]' | 
               ForEach-Object { $_.Node.Name }

$disableNames = $xml | Select-Xml -XPath '/Configuration/Notificationlist/*[text()="Disable"]' | 
                ForEach-Object { $_.Node.Name }

XPath表达式*[text()="SomeText"]给出了所有具有给定文本的文本子节点的元素。
要获取节点名,只需查询节点的Name属性。

相关问题