$xml = [xml] @'
<?xml version="1.0" encoding="UTF-8"?>
<group>
<product description="phone" id="1234/5678">
<item name="apple" version="50" />
<item name="banana" version="100" />
</product>
<product description="notebook" id="6666/7777">
<item name="orange" version="150" />
</product>
</group>
'@
$xml.group.product[0].item[0].name
works (returns 'apple'
), because the 1st product
element has 2 item
child elements.
However, $xml.group.product[1].item[0].name
does not work (returns $null
), because there is only one item
element.
How can I reliably access the first item
child element without having to know whether it happens to be the only one?
Your example xml isn't quite valid, so I'm going to use a slightly modified version:
$xml = [xml] @"
<?xml version="1.0" encoding="UTF-8"?>
<group>
<product description="phone" id="1234/5678">
<item name="apple" version="50" />
<item name="banana" version="100" />
</product>
<product description="notebook" id="6666/7777">
<item name="orange" version="150" />
</product>
</group>
"@
In your scenario, there's a PowerShell feature called Member Enumeration which applies to your first product
node and returns an array of all the child item
nodes, but for the second product
node it just returns the item
node itself:
PS> $xml.group.product[0].item.GetType().FullName
System.Object[]
PS> $xml.group.product[1].item.GetType().FullName
System.Xml.XmlElement
As a result you can index into the array from the first product
node, but not the XmlElement from the second, which gives the behaviour you've seen.
To fix this, what you could do is coerce the item
nodes into an array so that you can index into it even if there's only one item
:
PS> @($xml.group.product[0].item).GetType().FullName
System.Object[]
PS> @($xml.group.product[1].item).GetType().FullName
System.Object[]
PS> @($xml.group.product[1].item)[0].name
orange
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.