问题
I would like to get the node 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/@*")
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.
#text
-----
watch
24.28
2013-12-01
toy
22.34
2013-12-02
bread
24.12
2013-12-03
If I use any of the below commands I get no output.
[xml]$item = get-content pricefile.xml
$item.SelectNodes("//item/@*").parentnode
$item.SelectNodes("//item/@*") | where {$_.parentnode}
回答1:
Given an XmlAttribute object to start with, you can get parent element via OwnerElement property. Notice that ParentNode won't work here since its value is always empty on XmlAttribute :
λ $myXmlAttr = $item.SelectSingleNode("//item/@*")
λ $myXmlAttr.OwnerElement.LocalName
item
λ $myXmlAttr | Format-List -Property *
#text : watch
ParentNode :
Name : name
LocalName : name
NamespaceURI :
Prefix :
NodeType : Attribute
OwnerDocument : #document
Value : watch
SchemaInfo : System.Xml.XmlName
InnerText :
Specified : True
OwnerElement : item
InnerXml :
BaseURI :
ChildNodes : {#text}
PreviousSibling :
NextSibling :
Attributes :
FirstChild : #text
LastChild : #text
HasChildNodes : True
IsReadOnly : False
OuterXml : name="watch"
PreviousText :
回答2:
First, to select the element with the name attribute value toy:
$toy = $item.SelectSingleNode("//*[@name='toy']")
Since PowerShell is trying to be helpful, and expose the name attribute as a property on the object, we'll need to use the property accessor for the actual tag Name property:
$toy.get_Name()
回答3:
Here's the xpath way:
[xml]$item = @'
<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>
'@
(Select-XML -Xml $item -XPath "//item[@name=""toy""]").Node
(Select-XML -Xml $item -XPath "//item[@name=""toy""]").Node.get_Name()
回答4:
Here's another way to get the desired info:
$item.model.PriceData.Item | ? name -eq toy
来源:https://stackoverflow.com/questions/42851548/getting-the-element-name-of-an-attribute-in-xml-using-powershell