0
<item>
<food>
<snacks biscuit="mariegold">
</snacks>
</food>
</item>

In the above xml, I have to parse the snacks value. But I should not consider "biscuit" in the powershell script while parsing. without using "biscuit" term, i should parse the term "mariegold" using "snacks" in powershell. please give me some ideas.

  • You want to write a function where, with the given xml, you input "snacks" and it outputs "mariegold"? – Mathias R. Jessen Mar 10 '20 at 17:18
  • snacks has no value (or inner-text) but an attribute called 'biscuit'. also this is no valid xml that you could parse anyway (look at the node "food"). also you can't get "mariegold" without looking for "biscuit". I'd suggest you first look into how xml should look like and then maybe reconsider how the "snacks" or "food"-node should look like and what data they should be able to represent – D.J. Mar 10 '20 at 17:33

1 Answers1

1

If the intent is to get the value of attribute biscuit without knowing its name from the <snacks> element:

[xml] $xml = @'
<item>
    <food>
        <snacks biscuit="mariegold">
        </snacks>
    </food>
</item>
'@

$xml.item.food.snacks.Attributes.Value # -> 'mariegold'

The above relies on member-access enumeration to simply extract the values of all attributes, via the Attributes collection; since there is only one attribute in this case (biscuit), its value is returned.

If you're unexpectedly still running Windows PowerShell version 2, where member-access enumeration is not available, use the following instead:

$xml.item.food.snacks.Attributes | foreach { $_.Value } # -> 'mariegold'
mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thank you for this idea. I tried this, but it doesn't get the data 'mariegold'. It shows blank space. – Hari Varthini Mar 12 '20 at 06:08
  • @HariVarthini, that implies that you're running the long-obsolete version 2 of PowerShell - please see my update. If that is indeed the case, please be sure to tag your questions as `powershell-2.0` in the future, because many modern PowerShell techniques do not work in this version, so answers need to take this into account. – mklement0 Mar 12 '20 at 08:36