简体   繁体   中英

Obtain the value of one XML attribute using a different attribute as a key in Powershell

I am really lost doing something simple. I need to scan a couple of thousand files for a several specific items in each file. With the xml file below, I am trying to get the contents of the attribute "value, for a specific "property" name. So for instance, I just want to get the value of property name "MY_KEY_DATA1". I am able to select the node based on the below code, but I need to get the value of "314159" for the property name "MY_KEY_DATA1". In the below code I can get the node and print it out, but how to I read the specific attribute? I know I am doing it the hard way, there has got to be a simpler method.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<mydevice xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" dosid="02073" id="" name="MyTargetName">
<manager name="Module 1">
</manager>
<manager name="Module 2">
</manager>
<misc  name="Misc Name">
</misc>
<manager name="Module ABC">
</manager>
<modules>
<module group="Group1" name="name1">
</module>
<module group="Group2" name="name2">
</module>
<module group="Memory" name="myname">
<misc_data name= "MISC_DATA"  value = "42"/>
<property name="MY_KEY_DATA1" value="314159"/>
<property name="USELESS_DATA1" value="2"/>
<property name="MY_KEY_DATA1" value="2718"/>
</module>
</modules>
</mydevice>

--

$Testfile = 'xmltest2.xml'
$xml = [xml](Get-Content $Testfile)


$myNode2 =  $xml.SelectSingleNode("//modules/module[@group='Memory']")
Write-Output $myNode
Foreach ($xmlProperty in $myNode)  {

}

Once you have an XmlDocument type, you can select the target node and then access its attributes directly. You can use the SelectNodes (when there could be multiple nodes) or SelectSingleNode when one node is expected. An XPATH value will narrow down to the specific node that contains the target attribute value. Then you can simply access the attribute value using the member access operator . .

$Testfile = 'xmltest2.xml'
$xml = [xml](Get-Content $Testfile)
$xml.SelectNodes("//modules/module[@group='Memory']/property[@name='MY_KEY_DATA1']").value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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