PowerShell: How to Select XML Node by Attribute Value


Often you may want to use PowerShell to select a specific node of an XML file based on an attribute value.

You can use the following syntax to do so:

[xml]$my_xml = Get-Content my_data.xml

$my_xml.team.info.name | Where-Object { $_.id -eq 'M1209' }

This particular example selects the node with the structure team.info.name that has an id value of M1209.

Note: We use the Where-Object cmdlet to search through the contents of the XML file and return only the nodes that have an id attribute equal to ( -eq ) a specific value.

The following example shows how to use this syntax in practice.

Example: How to Use PowerShell to Select XML Node by Attribute Value

Suppose that we have an XML file named my_data.xml in our current directory.

We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to select only the <name> tag that contains an id value of M1209.

We can use the following syntax to do so:

[xml]$my_xml = Get-Content my_data.xml

$my_xml.team.info.name | Where-Object { $_.id -eq 'M1209' }

The following screenshot shows how to use this syntax in practice:

PowerShell select XML node by attribute value

Notice that this returns only the contents of the <name> tag where the id value is M1209.

The output also displays the text within the <name> tag, which is Mavs.

Feel free to use similar syntax to select any node from an XML file based on a specific attribute value.

Note: You can find the complete documentation for the Where-Object cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Update Content in XML File
PowerShell: How to Convert XML to String
PowerShell: How to Edit a JSON File

Leave a Reply