简体   繁体   中英

XML element name of an attribute using Powershell

I would like to get the xml element name of an attribute using powershell. Can anyone please let me know if we have a built in function for the same.

Following is my xml file called pricefile.xml

 <model type="model1" name="default" price="12.12" date="some_value">
  <PriceData>
    <item name="watch" price="24.28" date="2013-12-01"/>
    <item name="toy" price="22.34" date="2013-12-02"/>
    <item name="bread" price="24.12" date="2013-12-03"/>
  </PriceData>
 </model>

Say I want to get the element name "item" for the attribute "toy". How can I get this data?

This is what I have so far.

[xml]$item = get-content pricefile.xml
$item.SelectNodes("//item") | where {$_.name -like "toy"}

which gives me the below output, but I do not know how to get the element of the attribute from here or it's parent node.

name            price                   date                                             
----            -----                   ----                                             
toy             22.34                   2013-12-02   

If you'd like to get the parent node you can try this: ($item.SelectNodes("//item") | where {$_.name -like "toy"}).ParentNode

If you would like to access another attribute within your item element, you can do so like this: ($item.SelectNodes("//item") | where {$_.name -like "toy"}).price

You can access the XmlElement.Name Property property like so:

(($item.SelectNodes("//item")))[0].name

You can get it from XmlElement.LocalName property, for example :

λ $item = [xml]@"
>> <model type="model1" name="default" price="12.12" date="some_value">
>>   <PriceData>
>>     <item name="watch" price="24.28" date="2013-12-01"/>
>>     <item name="toy" price="22.34" date="2013-12-02"/>
>>     <item name="bread" price="24.12" date="2013-12-03"/>
>>   </PriceData>
>>  </model>
>> "@
λ $item.SelectNodes("//item") | where {$_.name -like "toy"} | select LocalName

LocalName
---------
item

λ $item.SelectNodes("//*[contains(@name,'toy')]") | select LocalName   

LocalName                                                              
---------                                                              
item                                                                   

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