Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing non-consistent XML-objects using Powershell

I'm trying to parse an XML which doesn't consist of uniform attributes. Example

<root>
<object>
  <name>Object1</name>
  <valueString>string</valueString>
</object>
<object>
  <name>Object2</name>
  <valueBoolean>true</valueBoolean>
</object>
</root>

The number of sub attributes is always the same but sometimes its a boolean and sometimes its a string and the tag name changes accordingly. The issue is not the type itself but, with Powershell, I have to know the tag name beforehand to obtain the value attached to it.

At the moment I'm doing something like this:

foreach($item in $items){
  if(!$item.object.valueString){
     $temp = $item.object.valueBoolean
  }
  else{
     $temp = $item.object.valueString
  }
  $properties = @{
      Name = $item.object.Name
      value = $temp
  }
}

This works but I would like a more elegant solution + at the moment it's quite rigid and you have to cater for each and every possibility.

Is there a better way ?

Cheers

like image 233
GradiusX Avatar asked May 08 '26 01:05

GradiusX


1 Answers

You can use ChildNodes property to access child elements by their order:

$xml=[xml]@'
<root>
  <object>
    <name>Object1</name>
    <valueString>string</valueString>
  </object>
  <object>
    <name>Object2</name>
    <valueBoolean>true</valueBoolean>
  </object>
</root>
'@
foreach($object in $xml.root.object){
    $value=$object.ChildNodes[1]
    [PSCustomObject]@{
        Name=$object.Name
        ValueName=$value.Name
        Value=$value.'#text'
    }
}
like image 128
user4003407 Avatar answered May 09 '26 15:05

user4003407



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!