这是snpdate.xml
<skata serial="GSI100-A-00103"/>
这是 test.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Clients xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<set>
<indexlist>
<index name="mario1" sn="GSI100-A-00100" status="ok" version="v49" />
<index name="mario2" sn="GSI100-A-00101" status="ok" version="v49" />
<index name="mario3" sn="GSI100-A-00102" status="ok" version="v49" />
<index name="mario4" sn="GSI100-A-00103" status="OFF" version="v49" />
<index name="mario5" sn="GSI100-A-00104" status="ok" version="v49" />
<index name="mario6" sn="GSI100-A-00105" status="ok" version="v49" />
<index name="mario7" sn="GSI100-A-00106" status="ok" version="v49" />
</indexlist>
</set>
</Clients>
$xmloff = New-Object System.Xml.XmlDocument
$xmlold = "C:\Program Files (x86)\GSI\Atreus\snupdate.xml"
$xmledit = "C:\Users\bigadmin\Desktop\Projects\AutoUpdate\test.xml"
[xml]$Xmlsn = Get-Content($xmlold) -Encoding UTF8 #open 1st xml
[xml]$Xmlnew = Get-Content($xmledit) -Encoding UTF8 #open 2st xml
$you = $Xmlsn.SelectSingleNode("//skata/@serial") #get value of serial element
$you.Value #prints correct value
$attr = $Xmlnew.SelectSingleNode("//Clients/set/indexlist/index[@sn='$you']/@status")
#from the second xml trying to get the value of status based on sn taking #the variable of $you. returns null.instead of OFF. if i manually insert
#[@sn='GSI100-A-00103'] instead of "$you" i get the correct result.
$attr.Value
我试图从第二个 xml 中获取基于 sn 的状态值,取$you
. 它返回 null 而不是 OK。如果我手动插入
[@sn='GSI100-A-00103']
而不是$you
我得到正确的结果。我想获取$you
带值的变量f.e.GSI100-A-00103
并在另一个 xml 上使用它来查找状态 = 关闭的新元素值。我认为问题是该变量是从另一个 xml 加载的?
您需要sn
与字符串$you.Value
而不是 XmlAttribute进行比较$you
。由于您需要检索带引号的字符串内的属性值,因此$()
使用了运算符。
$attr = $Xmlnew.SelectSingleNode("//Clients/set/indexlist/index[@sn='$($you.Value)']/@status")
解释:
在字符串中检索对象的属性时,变量扩展会在.
字符处停止。这些情况需要使用子表达式运算符$()
。运算符告诉 PowerShell 解析器根据.
字符重新评估解析模式,而不是将.propertyname
视为文字字符串。
您可以在下面的示例中看到这一点:
$obj = [pscustomobject]@{"Property" = "Value"}
"$obj.property" # Unexpected Results
@{Property=Value}.property
"$($obj.property)" # Expected Results
Value
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句