简体   繁体   English

Powershell XML 从另一个属性中获取具有特定值的属性值

[英]Powershell XML get attribute value with specific value from another attribute

HI i'm new to Powershell and i'm trying to read an xml file with some conditions, here is the file嗨,我是 Powershell 的新手,我正在尝试在某些条件下读取 xml 文件,这是文件

<file>
     <userlist>
         <user name="Martin" log="mr.martin@mail.com"></user>
         <user name="Tec" log="mr.tec@mail.com"></user>
         <user name="Obama" log="mr.obama@mail.com"></user>
     </userlist>
</file> 

What i want to do is to get in a variable my name from a specific log.我想要做的是从特定日志中获取我的名字的变量。 For exemple get name if log = mr.martin@mail.com what i tried was this例如,如果 log = mr.martin@mail.com,则获取名称我尝试的是这个

$PathXML="Path\conf.xml"
 $xml = New-Object -TypeName XML
 $xml.Load($PathXML)
$name = $xml.file.userlist.user | Select-Object -Property name | where log -eq "mr.martin@mail.com"

The problem is that it returns me my log instead of my name.问题是它返回我的日志而不是我的名字。 Thanks in advance for the help.在此先感谢您的帮助。

EDIT it doesn't return me my log but this @{name=Martin}编辑它不会返回我的日志,但这个 @{name=Martin}

EDIT V2编辑 V2

after more research i found that my result was an Hashtable so all i have to do get the name is:经过更多研究后,我发现我的结果是一个哈希表,所以我所要做的就是得到这个名字:

$var = $name.name

I'd use XPath.我会使用 XPath。 This one get's the name attribute directly:这个直接获取name属性:

$name = $xml.SelectSingleNode('//user[@log = "mr.martin@mail.com"]/@name')
Write-Host $name

This one gets the matching <user> element:这个得到匹配的<user>元素:

$name = $xml.SelectSingleNode('//user[@log = "mr.martin@mail.com"]')
Write-Host $user.name

Your approach would work better without the Select :如果没有Select ,您的方法会更好:

$user = $xml.file.userlist.user | where log -eq "mr.martin@mail.com"
Write-Host $user.name

With simple queries like this, using PowerShell's tools will be roughly on par with XPath, but when things a little get more complex, XPath will quickly be in the lead.通过像这样的简单查询,使用 PowerShell 的工具将与 XPath 大致相当,但是当事情变得更复杂时,XPath 将很快领先。 That's why I usually use XPath from the start.这就是为什么我通常从一开始就使用 XPath 的原因。 Also, XPath will be faster than a PowerShell pipeline, which could become relevant with larger XML files.此外,XPath 将比 PowerShell 管道更快,这可能与更大的 XML 文件相关。

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

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